Skip to content

Commit 28341f0

Browse files
committed
Add support for WebP decompression via the browser
1 parent b9aad79 commit 28341f0

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

src/compression/index.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import LZWDecoder from './lzw';
33
import JpegDecoder from './jpeg';
44
import DeflateDecoder from './deflate';
55
import PackbitsDecoder from './packbits';
6+
import WebImageDecoder from './webimage';
67

78
export function getDecoder(fileDirectory) {
89
switch (fileDirectory.Compression) {
@@ -20,6 +21,8 @@ export function getDecoder(fileDirectory) {
2021
return new DeflateDecoder();
2122
case 32773: // packbits
2223
return new PackbitsDecoder();
24+
case 50001:
25+
return new WebImageDecoder();
2326
default:
2427
throw new Error(`Unknown compression method identifier: ${fileDirectory.Compression}`);
2528
}

src/compression/webimage.js

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import BaseDecoder from './basedecoder';
2+
3+
/**
4+
* class WebImageDecoder
5+
*
6+
* This decoder uses the browsers image decoding facilities to read image
7+
* formats like WebP when supported.
8+
*/
9+
export default class WebImageDecoder extends BaseDecoder {
10+
constructor() {
11+
super();
12+
if (typeof createImageBitmap === 'undefined') {
13+
throw new Error('Cannot decode WebImage as `createImageBitmap` is not available');
14+
} else if (typeof document === 'undefined' && typeof OffscreenCanvas === 'undefined') {
15+
throw new Error('Cannot decode WebImage as neither `document` nor `OffscreenCanvas` is not available');
16+
}
17+
}
18+
19+
async decode(fileDirectory, buffer) {
20+
const blob = new Blob([buffer]);
21+
const imageBitmap = await createImageBitmap(blob);
22+
23+
let canvas;
24+
if (typeof document !== 'undefined') {
25+
canvas = document.createElement('canvas');
26+
canvas.width = imageBitmap.width;
27+
canvas.height = imageBitmap.height;
28+
} else {
29+
canvas = new OffscreenCanvas(imageBitmap.width, imageBitmap.height);
30+
}
31+
32+
const ctx = canvas.getContext('2d');
33+
ctx.drawImage(imageBitmap, 0, 0);
34+
35+
// TODO: check how many samples per pixel we have, and return RGB/RGBA accordingly
36+
// it seems like GDAL always encodes via RGBA which does not require a translation
37+
38+
return ctx.getImageData(0, 0, imageBitmap.width, imageBitmap.height).data.buffer;
39+
}
40+
}

0 commit comments

Comments
 (0)