gpt4 book ai didi

javascript - 使用 base64 编码/解码图像会破坏图像

转载 作者:数据小太阳 更新时间:2023-10-29 04:06:21 24 4
gpt4 key购买 nike

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

readAsBinaryString()

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.

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

示例代码 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
});

谢谢!

最佳答案

经过更多研究,我从 here 找到了答案我基本上需要将原始二进制文件包装在数组缓冲区中并将二进制字符转换为 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);
}

完整的示例代码是here

关于javascript - 使用 base64 编码/解码图像会破坏图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14967647/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com