Search code examples
javascripthtml5-canvasblobwebglweb-worker

How to resize image in webworker using OffscreenCanvas given local url and return resized data to main thread?


I want to offload image loading and resizing from main thread. After reading about this, it seems that my options are combination of fetch OffscreenCanvas and WebWorker.

Thus far I got to following stage within my webworker code:

  1. I pass imageUrl to web worker, that I then fetch, this gives me access to image data in it's blob format

  2. I then create an offscreen canvas in order to prepare for image resizing (canvas seems to be most common method I found online)

Example code looks like this

const response = await fetch(imageUrl);
const blob = await response.blob();
const canvas = new OffscreenCanvas();

And I am stuck at this stage. All examples I found so far use Image() to create image from url and access its width / height values, as well as load data onto canvas.

In my case I only have access to blob and since we are in webworker I can't create new Image(), hence I'm not sure how to proceed further?

Ideally what would happen next is we load image blob onto canvas, resize it to say 50% and return either base64 of the image or BlobUrl to main thread.


Solution

  • As you are not looking into all browsers support I guess, you might consider using createImageBitmap() method, which takes among the others Blob data and returns ImageBitmap. Which could be used to read height and width of the fetched image and to draw it on the off-screen canvas as well.

    More details here: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/createImageBitmap