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.
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
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With