[英]encode/decode image with base64 breaks image
我正在尝试编码和解码图像。 我正在使用FileReader的readAsDataURL方法将图像转换为base64。 然后将其转换回来我尝试使用readAsBinaryString()
和atob()
没有运气。 有没有另一种方法来保持图像没有base64编码吗?
readAsBinaryString()
开始读取指定Blob的内容,可能是文件。 当读取操作完成时,readyState将变为DONE,并且将调用onloadend回调(如果有)。 那时,result属性包含文件中的原始二进制数据。
知道我在这里做错了吗?
示例代码 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
});
谢谢!
URL.createObjectURL
期望Blob
(可以是File
)作为其参数。 不是字符串。 这就是URL.createObjectURL(file)
工作原理。
相反,您正在创建一个将file
读取为数据URL的FileReader
reader
,然后使用该数据URL创建另一个Blob
(具有相同的内容)。 然后你甚至创建一个reader2
来从刚构建的blob
获取二进制字符串 。 然而,无论是base64Image
URL字符串的一部分(即使btoa
-decoded到一个更大的字符串),也不是decoded.binary
字符串是vaild参数URL.createObjectURL
!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.