Previev图片:Blob还是FileReader?

kle*_*ium 6 javascript blob file-upload image filereader

我需要在将选择的图像发送到服务器之前显示它.我需要图像的宽度和高度.

BlobVS FileReader.我已经做了一些研究,但我想确保没有错过任何重要的东西,我用最好的方法.

Blob对象表示不可变的原始数据的类文件对象.Blob表示不一定采用JavaScript本机格式的数据.File接口基于Blob,继承blob功能并将其扩展为支持用户系统上的文件.

FileReader对象允许Web应用程序异步读取存储在用户计算机上的文件(或原始数据缓冲区)的内容,使用File或Blob对象指定要读取的文件或数据.

console.time("blob");
var img = new Image;
img.onload = function()
{
    $("img").attr("src", this.src);
    console.timeEnd("blob");
    doSomething(this.width, this.height);
    window.URL.revokeObjectURL(img.src);
}
img.src = window.URL.createObjectURL(file);


console.time("filereader");
var reader = new FileReader();
reader.onload = function(e)
{
    var img = new Image;
    img.src = e.target.result;
    img.onload = function()
    {
        $("img").attr("src", this.src);
        console.timeEnd("filereader");
        doSomething(this.width, this.height);
    }
    reader.readAsDataURL(file);
}
Run Code Online (Sandbox Code Playgroud)

结果(测试图像为14850x8000,6.41 MB):

            Firefox 39  Chrome 44   Opera 30    Internet Explorer 11
Blob        249ms       47ms        65ms        81ms
FileReader  2517ms      3693ms      2191ms      2679ms
Run Code Online (Sandbox Code Playgroud)
  • 两者都异步加载图像.
  • 两者都杀了浏览器几秒钟(Web Workers ftw).
  • FileReader直接返回内容(我现在不需要).
  • 虽然测试显示Blob速度比FileReader实际快25倍,但实际上速度仅提高了1.5/2倍(从选择文件到我看到加载图像的时间约为4s Blob,FileReader在Firefox中约为6s ).
  • 在Firefox中,如果我显示图像,并且我做了5分钟的其他操作,那么返回到网站,两个图像都将是黑色的.
  • 所有主流浏览器都支持这两种浏览器(我不需要readAsBinaryString).