Reading large images as thumbnails locally via HTML5 filereader

后端 未结 1 1872
感动是毒
感动是毒 2020-12-29 16:00

I am trying to load local images as thumbnails as explained here. My code is below.

This works fine for small images. However, when you try load larger images (e.g.

相关标签:
1条回答
  • 2020-12-29 16:48

    There is always a lag when you run something in the main UI thread which involves manipulating non-streaming data in huge blobs. The lag does not come from reading he data, but decoding and displaying the image in the browser UI as this involves synchronous UI operations pushing the large pixel array around in CPU and GPU memory. This is because <img> allocates and moves around memory in the blocks of actual image data size (width * height) which is very large amount for big images and unnecessary detailed to push it up to GPU for just showing it on the screen (causes the lag of several milliseconds).

    You can most likely optimize your use case by shrinking the image to displayable size while reading it

    • Using a pure Javascript JPEG decoder where main event loop reads the file in chunks and posts chunks to WebWorker background thread for decoding. One example decoder library https://github.com/notmasteryet/jpgjs/blob/master/jpg.js

    • Allocate a <canvas> element where the WebWorker posts backs the resulting pixels progressively. This canvas element does not need to match the actual image size (see below)

    • Also you can scale down the images in the WebWorker while reading them in pure Javascript http://www.grantgalitz.org/image_resize/ - lessening the need to push the pixels to GPU as you are not going to fit the big image on the monitor as 1:1 pixel mapping in the first place

    • WebWorker and main thread can push data around using copy-free Transferable objects https://developer.mozilla.org/en-US/docs/DOM/Using_web_workers#Passing_data_by_transferring_.C2.A0ownership_%28transferable_objects%29

    However, though the solution described here is near perfect, to implement this one needs to possess advanced Javascript skills and the solution is not going to be legacy compatible (read: Microsoft).

    0 讨论(0)
提交回复
热议问题