Skip to content

Commit

Permalink
feat: support converting images in a web worker
Browse files Browse the repository at this point in the history
  • Loading branch information
cvbuelow committed Jun 20, 2024
1 parent c26f985 commit 7afcae4
Showing 1 changed file with 3 additions and 20 deletions.
23 changes: 3 additions & 20 deletions formats-browser.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,10 @@
const initializeCanvas = ({ width, height }) => {
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;

return canvas;
};

const convert = async ({ data, width, height }, ...blobArgs) => {
const canvas = initializeCanvas({ width, height });
const convert = async ({ data, width, height }, type, quality) => {
const canvas = new OffscreenCanvas(width, height);

const ctx = canvas.getContext('2d');
ctx.putImageData(new ImageData(data, width, height), 0, 0);

const blob = await new Promise((resolve, reject) => {
canvas.toBlob(blob => {
if (blob) {
return resolve(blob);
}

return reject(new Error('failed to convert the image'));
}, ...blobArgs);
});

const blob = await canvas.convertToBlob({ type, quality })
const arrayBuffer = await blob.arrayBuffer();

return new Uint8Array(arrayBuffer);
Expand Down

0 comments on commit 7afcae4

Please sign in to comment.