Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit c4dbdba

Browse files
author
evanwashere
committed
update png decoder
1 parent b4aad9d commit c4dbdba

File tree

3 files changed

+49
-1
lines changed

3 files changed

+49
-1
lines changed

ImageScript.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import v2 from './v2/framebuffer.mjs';
22
import * as png from './utils/png.js';
33
import * as svglib from './utils/wasm/svg.js';
44
import * as giflib from './utils/wasm/gif.js';
5+
import * as pnglib from './utils/wasm/png.js';
56
import * as fontlib from './utils/wasm/font.js';
67
import * as jpeglib from './utils/wasm/jpeg.js';
78

@@ -1024,7 +1025,7 @@ export class Image {
10241025
}
10251026

10261027
if (ImageType.isPNG(view)) { // PNG
1027-
const {width, height, pixels} = await png.decode(data);
1028+
const {width, height, framebuffer: pixels} = pnglib.decode(data);
10281029
image = new Image(width, height);
10291030
image.bitmap.set(pixels);
10301031
} else if (ImageType.isJPEG(view)) { // JPEG

utils/wasm/png.js

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
let wasm_mod;
2+
let ref = { deref() { } };
3+
4+
{
5+
const path = new URL(import.meta.url.replace('.js', '.wasm'));
6+
wasm_mod = new WebAssembly.Module(await ('file:' === path.protocol ? Deno.readFile(path) : fetch(path).then(r => r.arrayBuffer())));
7+
}
8+
9+
function wasm() {
10+
let u8;
11+
12+
const {
13+
wfree, walloc, decode, memory,
14+
width: wwidth, height: wheight,
15+
} = new WebAssembly.Instance(wasm_mod, {
16+
env: {
17+
emscripten_notify_memory_growth() {
18+
u8 = new Uint8Array(memory.buffer);
19+
},
20+
},
21+
}).exports;
22+
23+
u8 = new Uint8Array(memory.buffer);
24+
25+
return {
26+
decode(buffer) {
27+
const ptr = walloc(buffer.length);
28+
29+
u8.set(buffer, ptr);
30+
const status = decode(ptr, buffer.length);
31+
32+
wfree(ptr);
33+
if (0 > status) throw new Error(`png: failed to decode (${status})`);
34+
35+
const width = wwidth();
36+
const height = wheight();
37+
const framebuffer = u8.slice(status, status + 4 * width * height);
38+
39+
wfree(status);
40+
return { width, height, framebuffer };
41+
},
42+
};
43+
}
44+
45+
export function decode(buffer) {
46+
return (ref.deref() || (ref = new WeakRef(wasm())).deref()).decode(buffer);
47+
}

utils/wasm/png.wasm

101 KB
Binary file not shown.

0 commit comments

Comments
 (0)