ag-psd icon indicating copy to clipboard operation
ag-psd copied to clipboard

Web worker example is incorrect

Open pastelmind opened this issue 1 month ago • 2 comments

The web worker example added in 25ee6477dac2295260b6c3d6a9d34a61cb7736d8 (see #13) is incorrect. The new Image() constructor is not available in a web worker context:

Uncaught ReferenceError: Image is not defined

The web worker test didn't catch this because it never called createCanvasFromData() at all.

const createCanvas = (width, height) => {
  return new OffscreenCanvas(width, height);
};

const createCanvasFromData = (data) => {
  // This should fail, but didn't because the function is never called
  // for the test PSD file
  const image = new Image();
  image.src = 'data:image/jpeg;base64,' + agPsd.byteArrayToBase64(data);
  const canvas = new OffscreenCanvas(image.width, image.height);
  canvas.getContext('2d').drawImage(image, 0, 0);
  return canvas;
};

agPsd.initializeCanvas(createCanvas, createCanvasFromData);

The typical way to draw an image file to a OffscreenCanvas is to convert it to an ImageBitmap and draw it to an OffscreenCanvas. However, this is an async operation:

const imageBitmap = await createImageBitmap(blob);
const canvas = new OffscreenCanvas(imageBitmap.width, imageBitmap.height);
canvas.getContext('2d').drawImage(imageBitmap, 0, 0);

The current implementation requires createCanvasFromData() to be synchronous, which makes it incompatible with web workers.

https://github.com/Agamnentzar/ag-psd/blob/f3662b05d2da917c4b99be2e809fc6397ed15ba2/src/imageResources.ts#L1268-L1270

Perhaps web workers could set useRawThumbnail: true and decode the thumbnail ArrayBuffers in the UI thread. I haven't tested this, though.

pastelmind avatar Nov 28 '25 09:11 pastelmind

If you use useRawThumbnail: true then createCanvasFromData will never be called, so it will solve the issue. But I'll redesign this, there's no longer need for using Image for decoding the thumbnail.

Agamnentzar avatar Nov 28 '25 16:11 Agamnentzar

Published version 29.0.0 with removed need for createCanvasFromData helper

Agamnentzar avatar Dec 01 '25 00:12 Agamnentzar