encode/decode image with base64 breaks image

前端 未结 2 1274
半阙折子戏
半阙折子戏 2020-12-05 12:19

I am trying to encode and decode an image. I am using the FileReader\'s readAsDataURL method to convert the image to base64. Then to convert it back I have tried using

相关标签:
2条回答
  • 2020-12-05 13:02

    After some more research I found the answer from here I basically needed to wrap the raw binary in an arraybuffer and convert the binary chars to Unicode.

    This is the code that was missing,

        var binaryImg = atob(base64Image);
        var length = binaryImg.length;
        var ab = new ArrayBuffer(length);
        var ua = new Uint8Array(ab);
        for (var i = 0; i < length; i++) {
            ua[i] = binaryImg.charCodeAt(i);
        }
    

    The full sample code is here

    0 讨论(0)
  • 2020-12-05 13:04

    URL.createObjectURL expects a Blob (which can be a File) as its argument. Not a string. That's why URL.createObjectURL(file) works.

    Instead, you are creating a FileReader reader that reads file as a data url, then you use that data url to create another Blob (with the same contents). And then you even create a reader2 to get a binary string from the just constructed blob. However, neither the base64Image url string part (even if btoa-decoded to a larger string) nor the decoded.binary string are vaild arguments to URL.createObjectURL!

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