7

I need to display the choosed image before sending it to the server. I need the width and height of the image.

Blob vs FileReader. I've done some research, but I want to make sure have missed nothing important and I use the best way.

A Blob object represents a file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system.

The FileReader object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read.

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

Results (test image is 14850x8000, 6.41 MB):

            Firefox 39  Chrome 44   Opera 30    Internet Explorer 11
Blob        249ms       47ms        65ms        81ms
FileReader  2517ms      3693ms      2191ms      2679ms
  • Both load the image asynchronously.
  • Both kill the browser for some seconds (Web Workers ftw).
  • Only FileReader returns the content directly (which I don't need now).
  • Although the test showed that Blob is 25x faster than FileReader, in fact, it's only ~1.5/2x faster (from the time choosing the file to the time I see the loaded image is ~4s for Blob, ~6s for FileReader in Firefox).
  • In Firefox, if I display the images, and I do something else for 5 minutes, then return to the site, both images will be black.
  • Both are supported in all major browsers (I don't need readAsBinaryString).
Jir
  • 2,985
  • 8
  • 44
  • 66
klenium
  • 2,468
  • 2
  • 24
  • 47

0 Answers0