mirror of
https://github.com/GoogleChromeLabs/squoosh.git
synced 2025-11-13 09:17:20 +00:00
@@ -30,7 +30,28 @@ export async function canvasEncode(data: ImageData, type: string, quality?: numb
|
|||||||
if (!ctx) throw Error('Canvas not initialized');
|
if (!ctx) throw Error('Canvas not initialized');
|
||||||
ctx.putImageData(data, 0, 0);
|
ctx.putImageData(data, 0, 0);
|
||||||
|
|
||||||
const blob = await new Promise<Blob | null>(r => canvas.toBlob(r, type, quality));
|
let blob: Blob | null;
|
||||||
|
|
||||||
|
if ('toBlob' in canvas) {
|
||||||
|
blob = await new Promise<Blob | null>(r => canvas.toBlob(r, type, quality));
|
||||||
|
} else {
|
||||||
|
// Welcome to Edge.
|
||||||
|
// TypeScript thinks `canvas` is 'never', so it needs casting.
|
||||||
|
const dataUrl = (canvas as HTMLCanvasElement).toDataURL(type, quality);
|
||||||
|
const result = /data:([^;]+);base64,(.*)$/.exec(dataUrl);
|
||||||
|
|
||||||
|
if (!result) throw Error('Data URL reading failed');
|
||||||
|
|
||||||
|
const outputType = result[1];
|
||||||
|
const binaryStr = atob(result[2]);
|
||||||
|
const data = new Uint8Array(binaryStr.length);
|
||||||
|
|
||||||
|
for (let i = 0; i < data.length; i += 1) {
|
||||||
|
data[i] = binaryStr.charCodeAt(i);
|
||||||
|
}
|
||||||
|
|
||||||
|
blob = new Blob([data], { type: outputType });
|
||||||
|
}
|
||||||
|
|
||||||
if (!blob) throw Error('Encoding failed');
|
if (!blob) throw Error('Encoding failed');
|
||||||
return blob;
|
return blob;
|
||||||
|
|||||||
Reference in New Issue
Block a user