Build a Image to Base64 Code or String Converter From URL in Browser Using HTML5 & Javascript Full Project For Beginners

 

 

<center>
  <span>Directions:<br/>
  after the image is visible in the canvas, click the "convert to base64" button and it should autopopulate with the 'data:' string for the image!<br />uses <a href="https://crossorigin.me">crossorigin.me</a> to keep the canvas... pure?</span><br /><br /><br />
  Image URL: <input id="txtURL" type="text" />
<input id="bLoad" type="button" value="load" />
<br /><br /><canvas id="canvasMain"></canvas>
<br /><br /><input id="bBase64" type="button" value="convert to base64"><br />
<textarea cols=40 rows=15 id="txtArea"></textarea>
</center>

 

 

var bLoad = document.getElementById("bLoad");
var bBase64 = document.getElementById("bBase64");
var txtArea = document.getElementById("txtArea");
var canvas = document.getElementById("canvasMain");

canvas.style.backgroundColor = "#000";

var url = "";

bLoad.onclick = function() {
  url = document.getElementById("txtURL").value;
  var image = new Image();
  image.crossOrigin = "anonymous";
  image.onload = function() {
    canvas.width = image.width;
    canvas.height = image.height;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(image, 0, 0);
  };
  image.src = "https://crossorigin.me/" + url;
}

bBase64.onclick = function() {
  txtArea.value = canvas.toDataURL();
}

 

Leave a Reply