Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for WebP decompression via the browser #194

Merged
merged 4 commits into from
Jan 20, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/compression/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,4 @@ addDecoder(7, () => import('./jpeg.js').then((m) => m.default));
addDecoder([8, 32946], () => import('./deflate.js').then((m) => m.default));
addDecoder(32773, () => import('./packbits.js').then((m) => m.default));
addDecoder(34887, () => import('./lerc.js').then((m) => m.default));
addDecoder(50001, () => import('./webimage.js').then((m) => m.default));
40 changes: 40 additions & 0 deletions src/compression/webimage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import BaseDecoder from './basedecoder.js';

/**
* class WebImageDecoder
*
* This decoder uses the browsers image decoding facilities to read image
* formats like WebP when supported.
*/
export default class WebImageDecoder extends BaseDecoder {
constructor() {
super();
if (typeof createImageBitmap === 'undefined') {
throw new Error('Cannot decode WebImage as `createImageBitmap` is not available');
} else if (typeof document === 'undefined' && typeof OffscreenCanvas === 'undefined') {
throw new Error('Cannot decode WebImage as neither `document` nor `OffscreenCanvas` is not available');
}
}

async decode(fileDirectory, buffer) {
const blob = new Blob([buffer]);
const imageBitmap = await createImageBitmap(blob);

let canvas;
if (typeof document !== 'undefined') {
canvas = document.createElement('canvas');
canvas.width = imageBitmap.width;
canvas.height = imageBitmap.height;
} else {
canvas = new OffscreenCanvas(imageBitmap.width, imageBitmap.height);
}

const ctx = canvas.getContext('2d');
ctx.drawImage(imageBitmap, 0, 0);

// TODO: check how many samples per pixel we have, and return RGB/RGBA accordingly
// it seems like GDAL always encodes via RGBA which does not require a translation

return ctx.getImageData(0, 0, imageBitmap.width, imageBitmap.height).data.buffer;
}
}