I need to display the selected image before sending it to the server. I need the width and height of the image.
Blob vs FileReader . I have done some research, but I want to make sure that I missed anything important, and I use the best way.
A blob is a file object of immutable raw data. Blob is data that is not necessarily in JavaScript format. The File interface is based on Blob, inherits the functionality of blob and extends it to support files in the user system.
The FileReader object allows web applications to asynchronously read the contents of files (or source buffers) stored on a user 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 - 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 in a few seconds (ftw web workers).
- Only
FileReader returns the content directly (which I donβt need right now). - Although the test showed that
Blob is 25 times faster than FileReader , in fact it is only ~ 1.5 / 2x faster (from the moment I select the file until I see the downloaded image ~ 4 s for Blob , ~ 6s for FileReader in Firefox). - In Firefox, if I display images and I do something else for 5 minutes and then return to the site, both images will be black.
- Both are supported in all major browsers (I don't need readAsBinaryString ).
source share