简体   繁体   中英

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.

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

在此输入图像描述

 var element = new Image();
 element.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";

If you wants to add id to your body:

 document.body.appendChild(element);

You have to use appendChild on the parent element of where you want to display the image. It will be automatically loaded.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM