Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create base64 encoded images with JavaScript

Since images are data, we can write our code as

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />

Now my point is: can we create that base64 data with javascript? Is there any framework for it?

My actual requirement is that I have a string like "Cow" and I want it as an image.

Note: I do not want a server call for it. I know I can call server side code by passing "Cow" as a parameter. My server side code can generate that image, but I want do this from the browser with JavaScript.

like image 540
Partha Sarathi Ghosh Avatar asked Feb 08 '23 02:02

Partha Sarathi Ghosh


2 Answers

You can create an image with canvas. There are many canvas frameworks which can help you. Then you can "export" your canvas to base64 string.

Try this sample with jCanvas:

HTML

<p>
  Result:
</p>
<p>
  <textarea id="result" cols="60" rows="10"></textarea>
</p>
<p>
  <input id="click" type="button" value="Convert to base64">
</p>
<p>
  Canvas<br><canvas id="myCanvas" width="100" height="100"/>
</p>

JavaScript

$(function(){

  var canvas = document.getElementById("myCanvas");
  var ctx = canvas.getContext("2d");
  ctx.fillStyle = "#FF0000";
  ctx.fillRect(0, 0, 80, 80);

  $('#click').click(function() {
    $('#result').html($("canvas").getCanvasImage());
  });
});

Demo

enter image description here

like image 145
Ali Mamedov Avatar answered Feb 10 '23 23:02

Ali Mamedov


I hope I got your question right. You want the actual data and not the uri??

I found this small snippet from MuniR, I think it is what you wanted.

The thing is we cannot seem to get away from the canvas, create it with the size of the image, paint the image and use the canvas object to store it!!-Not necessarily USE it... Hope it helps, and good luck

function getBase64FromImageUrl(url) {
    var img = new Image();

    img.setAttribute('crossOrigin', 'anonymous');

    img.onload = function () {
        var canvas = document.createElement("canvas");
        canvas.width =this.width;
        canvas.height =this.height;

        var ctx = canvas.getContext("2d");
        ctx.drawImage(this, 0, 0);

        var dataURL = canvas.toDataURL("image/png");

        alert(dataURL.replace(/^data:image\/(png|jpg);base64,/, ""));
    };

    img.src = url;
}
like image 41
Sune Christiansen Avatar answered Feb 10 '23 23:02

Sune Christiansen