|
| 1 | +import BaseDecoder from './basedecoder.js'; |
| 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