[removed] Render PNG stored as Uint8Array onto Canvas element without Data URI

后端 未结 3 1507
面向向阳花
面向向阳花 2020-12-29 04:51

I\'m trying to render a PNG image that is stored in a javascript Uint8Array. The code that I originally tried was the following:

var imgByteStr         


        
3条回答
  •  無奈伤痛
    2020-12-29 05:02

    If you have the PNG data in memory (which I think is what you're describing) then you can create an image from it. In HTML it would look like:

     
    

    In JavaScript you can do the same:

    var image = document.createElement('img');
        image.src = 'data:image/png;base64,' + base64Data;
    

    Note that you can change the MIME type if you don't have PNG data.

    You could then draw the image onto your canvas using context.drawImage(image, 0, 0) or similar.

    So the remaining part of the puzzle is to encode the contents of your Uint8Array into Base 64 data.

    var array = new Uint8Array(),
        base64Data = btoa(String.fromCharCode.apply(null, array));
    

    The function btoa isn't standard, so some browsers might not support it. However it seems that most do. Otherwise you might find some code I use helpful.

    I haven't tested any of this myself!

提交回复
热议问题