使用base64编码/解码图像中断图像 [英] encode/decode image with base64 breaks image

查看:262
本文介绍了使用base64编码/解码图像中断图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对图像进行编码和解码。我正在使用FileReader的readAsDataURL方法将图像转换为base64。然后将其转换回来,我尝试使用 readAsBinaryString() atob(),但没有运气。有没有另一种方法可以在没有base64编码的情况下保留图像?

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 readAsBinaryString() and atob() with no luck. Is there another way to persist images without base64 encoding them?


readAsBinaryString()

开始读取指定Blob的内容,该内容可能是
文件。当读取操作完成时,readyState将变为
DONE,并且将调用onloadend回调(如果有)。在
时间,结果属性包含文件中的原始二进制数据。

Starts reading the contents of the specified Blob, which may be a File. When the read operation is finished, the readyState will become DONE, and the onloadend callback, if any, will be called. At that time, the result attribute contains the raw binary data from the file.

知道我在做什么这里错了吗?

Any idea what I'm doing wrong here?

示例代码
http://jsfiddle.net/qL86Z/3/

$("#base64Button").on("click", function () {
    var file = $("#base64File")[0].files[0]
    var reader = new FileReader();

    // callback for readAsDataURL
    reader.onload = function (encodedFile) {
        console.log("reader.onload");
        var base64Image = encodedFile.srcElement.result.split("data:image/jpeg;base64,")[1];
        var blob = new Blob([base64Image],{type:"image/jpeg"});
        var reader2 = new FileReader();

        // callback for readAsBinaryString
        reader2.onloadend = function(decoded) {
            console.log("reader2.onloadend");
            console.log(decoded); // this should contain binary format of the image

            // console.log(URL.createObjectURL(decoded.binary)); // Doesn't work
        };
        reader2.readAsBinaryString(blob);

        // console.log(URL.createObjectURL(atob(base64Image))); // Doesn't work

    };
    reader.readAsDataURL(file);
    console.log(URL.createObjectURL(file)); // Works
});

谢谢!

推荐答案

经过一些研究,我找到了答案来自这里
我基本上需要将原始二进制文件包装在arraybuffer中并将二进制字符转换为Unicode。

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.

这是缺少的代码,

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

完整的示例代码是这里

这篇关于使用base64编码/解码图像中断图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆