Image file (URL) -> base64 String (converter)

In this example below you will see how to do a Image file (URL) -> base64 String (converter) with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by alan8r, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright alan8r ©
  • HTML
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>Image file (URL) -> base64 String (converter)</title>
  
  
  
  
  
</head>

<body>

  <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>
  
  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/alan8r/image-file-url-andgt-base64-string-converter-akroZb */
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();
}

Comments