2013-02-19 222 views
7

我正在尝试编码和解码图像。我正在使用FileReader的readAsDataURL方法将图像转换为base64。然后将其转换回来,我尝试过使用readAsBinaryString()atob(),但没有运气。有没有其他的方式来保持图像没有base64编码他们?带有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 
}); 

谢谢!

+0

在浏览器这个例子中工作? TypeError:encodedFile.srcElement未定义 – cIph3r 2013-02-19 23:35:41

+0

我正在使用Chrome进行测试,但我需要它在最新的Android和iOS浏览器中工作。 – sissonb 2013-02-19 23:37:20

回答

13

经过一些更多的研究,我发现从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

1

URL.createObjectURL预计Blob(可以是File)作为它的参数。不是一个字符串。这就是为什么URL.createObjectURL(file)有效。

相反,你要创建一个FileReaderreader读取file作为数据URL,然后使用这些数据的URL创建另一个Blob(内容相同)。然后你甚至创建一个reader2从刚刚构建的blob得到一个二进制字符串。但是,base64Image url字符串部分(即使btoa被解码为更大的字符串)也不是decoded.binary字符串都是URL.createObjectURL的vaild参数!

+0

虽然可以将'base64Image'转换回原始文件吗?我基本上试图撤销'reader.readAsDataURL(file);'用'readAsBinaryString()'或'atob()'做的事情。 – sissonb 2013-02-20 00:31:17

+0

'var blob = new Blob([base64Image],{type:“image/jpeg”});'应该这样做吗?尝试'URL.createObjectURL(blob);' – Bergi 2013-02-20 00:36:25

+0

它显示'URL.createObjectURL(blob)的破碎图像;'我在这里更新了JSFiddle,http://jsfiddle.net/qL86Z/7/ 这里是一个截屏视频破碎的图像。 http://screencast.com/t/vVVGNTvo – sissonb 2013-02-20 00:41:51