Convert and insert Base64 data to Canvas in Javascript

前端 未结 2 576
故里飘歌
故里飘歌 2020-12-29 13:32

I get a buffer of data represent an image in Base64. The data I got (represent image in base64) (part of the data)

193,109,51,74,182,71,212,38,78,62,211,48,81,

相关标签:
2条回答
  • 2020-12-29 14:03

    http://localhost:994/%FF%...... cannot be drawn on canvas.
    Your data sould look like "data:image/png;base64,iVBORw0..."
    If they look like this then they are ready for use without base64 decoding. You simply draw them directly using context.drawImage

    0 讨论(0)
  • 2020-12-29 14:09

    You don't need to "decode" a base64 string to draw it in a canvas, just assign it to an image source and draw that image in your canvas.

    Something like this:

    var canvas = document.getElementById('canvas');
    var context = canvas.getContext('2d');
    var img = new Image();
    
    img.onload = function() {
      context.drawImage(this, 0, 0, canvas.width, canvas.height);
    }
    
    img.src = "data:image/gif;base64,R0lGODlhDwAPAKECAAAAzMzM/////wAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLlN48CXF8m2iQ3YmmKqVlRtW4MLwWACH+H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw==";
    <canvas id="canvas" width="50" height="50"></canvas>

    Make sure that your base64 string starts with the data:image/gif;base64, part.

    image/jpeg, image/png, etc.. Depending on your encoded image format.

    0 讨论(0)
提交回复
热议问题