@jimp/wasm-jpeg2000 0.0.0-stage → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/OPENJPEG-LICENSE +39 -0
- package/README.md +111 -2
- package/dist/browser/codestream.d.ts +29 -0
- package/dist/browser/codestream.d.ts.map +1 -0
- package/dist/browser/codestream.js +129 -0
- package/dist/browser/codestream.js.map +1 -0
- package/dist/browser/index.d.ts +71 -0
- package/dist/browser/index.d.ts.map +1 -0
- package/dist/browser/index.js +216 -0
- package/dist/browser/index.js.map +1 -0
- package/dist/browser/load-wasm-browser.d.mts.map +1 -0
- package/dist/browser/load-wasm-browser.mjs.map +1 -0
- package/dist/browser/load-wasm.d.ts +6 -0
- package/dist/browser/load-wasm.js +17 -0
- package/dist/browser/openjpegwasm.wasm +0 -0
- package/dist/browser/package.json +3 -0
- package/dist/esm/codestream.d.ts +29 -0
- package/dist/esm/codestream.d.ts.map +1 -0
- package/dist/esm/codestream.js +129 -0
- package/dist/esm/codestream.js.map +1 -0
- package/dist/esm/index.d.ts +71 -0
- package/dist/esm/index.d.ts.map +1 -0
- package/dist/esm/index.js +216 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/load-wasm.d.ts +3 -0
- package/dist/esm/load-wasm.d.ts.map +1 -0
- package/dist/esm/load-wasm.js +9 -0
- package/dist/esm/load-wasm.js.map +1 -0
- package/dist/esm/package.json +3 -0
- package/package.json +76 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2018 Oliver Moran
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/OPENJPEG-LICENSE
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* The copyright in this software is being made available under the 2-clauses
|
|
3
|
+
* BSD License, included below. This software may be subject to other third
|
|
4
|
+
* party and contributor rights, including patent rights, and no such rights
|
|
5
|
+
* are granted under this license.
|
|
6
|
+
*
|
|
7
|
+
* Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium
|
|
8
|
+
* Copyright (c) 2002-2014, Professor Benoit Macq
|
|
9
|
+
* Copyright (c) 2003-2014, Antonin Descampe
|
|
10
|
+
* Copyright (c) 2003-2009, Francois-Olivier Devaux
|
|
11
|
+
* Copyright (c) 2005, Herve Drolon, FreeImage Team
|
|
12
|
+
* Copyright (c) 2002-2003, Yannick Verschueren
|
|
13
|
+
* Copyright (c) 2001-2003, David Janssens
|
|
14
|
+
* Copyright (c) 2011-2012, Centre National d'Etudes Spatiales (CNES), France
|
|
15
|
+
* Copyright (c) 2012, CS Systemes d'Information, France
|
|
16
|
+
*
|
|
17
|
+
* All rights reserved.
|
|
18
|
+
*
|
|
19
|
+
* Redistribution and use in source and binary forms, with or without
|
|
20
|
+
* modification, are permitted provided that the following conditions
|
|
21
|
+
* are met:
|
|
22
|
+
* 1. Redistributions of source code must retain the above copyright
|
|
23
|
+
* notice, this list of conditions and the following disclaimer.
|
|
24
|
+
* 2. Redistributions in binary form must reproduce the above copyright
|
|
25
|
+
* notice, this list of conditions and the following disclaimer in the
|
|
26
|
+
* documentation and/or other materials provided with the distribution.
|
|
27
|
+
*
|
|
28
|
+
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
|
|
29
|
+
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
30
|
+
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
|
31
|
+
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
|
|
32
|
+
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
|
33
|
+
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
|
34
|
+
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
|
35
|
+
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
|
36
|
+
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
|
37
|
+
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
|
38
|
+
* POSSIBILITY OF SUCH DAMAGE.
|
|
39
|
+
*/
|
package/README.md
CHANGED
|
@@ -1,3 +1,112 @@
|
|
|
1
|
-
#
|
|
1
|
+
# `@jimp/wasm-jpeg2000`
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A format plugin for Jimp that adds support for JPEG 2000 images using [OpenJPEG](https://github.com/uclouvain/openjpeg), as compiled to WebAssembly by [`@cornerstonejs/codec-openjpeg`](https://www.npmjs.com/package/@cornerstonejs/codec-openjpeg).
|
|
4
|
+
|
|
5
|
+
> NOTE: Only works in esm environments.
|
|
6
|
+
|
|
7
|
+
## Usage
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm install jimp @jimp/core @jimp/wasm-jpeg2000
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import { createJimp } from "@jimp/core";
|
|
15
|
+
import { defaultFormats, defaultPlugins } from "jimp";
|
|
16
|
+
import jpeg2000, { j2c, jpx } from "@jimp/wasm-jpeg2000";
|
|
17
|
+
|
|
18
|
+
// A custom jimp that supports JPEG 2000
|
|
19
|
+
const Jimp = createJimp({
|
|
20
|
+
formats: [...defaultFormats, jpeg2000, j2c, jpx],
|
|
21
|
+
plugins: defaultPlugins,
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
const image = await Jimp.read("passport-photo.jp2");
|
|
25
|
+
const thumbnail = await Jimp.read("huge-scan.jp2", {
|
|
26
|
+
// Decode at 1/8th of the size, without decoding the full image
|
|
27
|
+
"image/jp2": { reduce: 3 },
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
await image.write("lossless.jp2");
|
|
31
|
+
await image.write("smaller.jp2", { compressionRatio: 20 });
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Each export adds one MIME type. Add the ones you need:
|
|
35
|
+
|
|
36
|
+
| Export | MIME type | Files | Read | Write |
|
|
37
|
+
| ---------- | ----------- | ---------- | ---- | ----- |
|
|
38
|
+
| `jpeg2000` | `image/jp2` | .jp2 | ✓ | ✓ |
|
|
39
|
+
| `j2c` | `image/j2c` | .j2c, .j2k | ✓ | ✓ |
|
|
40
|
+
| `jpx` | `image/jpx` | .jpx, .jpf | ✓ | |
|
|
41
|
+
|
|
42
|
+
`write` picks the format from the file extension, which isn't known for .j2c and .j2k, so use `getBuffer("image/j2c")` for codestreams.
|
|
43
|
+
|
|
44
|
+
### Supported images
|
|
45
|
+
|
|
46
|
+
- Grayscale and RGB, including YCbCr with 4:2:0 or 4:2:2 chroma subsampling
|
|
47
|
+
- 1 to 16 bits per sample, signed or unsigned, scaled to 8 bits
|
|
48
|
+
- An ICC profile in a JP2 or JPX is read into `image.iccProfile`
|
|
49
|
+
|
|
50
|
+
Images with alpha (2 or 4 components) or more components aren't supported, and throw an error.
|
|
51
|
+
Writing always uses 8-bit RGB without alpha: transparent pixels are composited onto `image.background`, and images in another colour space (like Display P3) are converted to sRGB.
|
|
52
|
+
|
|
53
|
+
### Options
|
|
54
|
+
|
|
55
|
+
Decode options, passed to `Jimp.read` under the MIME type:
|
|
56
|
+
|
|
57
|
+
| Option | Default | Description |
|
|
58
|
+
| ------------------- | ------- | ------------------------------------------------------------------------------------ |
|
|
59
|
+
| `reduce` | `0` | Decode at a lower resolution: each step halves the width and height |
|
|
60
|
+
| `layers` | `0` | Decode only the first quality layers, for a lower quality preview. `0` decodes all |
|
|
61
|
+
| `maxResolutionInMP` | `100` | Reject images larger than this many megapixels (after `reduce`) before decoding them |
|
|
62
|
+
|
|
63
|
+
Encode options, passed to `write` or `getBuffer`:
|
|
64
|
+
|
|
65
|
+
| Option | Default | Description |
|
|
66
|
+
| ------------------ | ------- | ------------------------------------------------------------------------------------------ |
|
|
67
|
+
| `compressionRatio` | `1` | Target size as a ratio of the uncompressed RGB pixels, e.g. `20` for 20:1. `1` is lossless |
|
|
68
|
+
| `decompositions` | `5` | Wavelet levels, which decoders can `reduce` by. Limited to what the image's size allows |
|
|
69
|
+
|
|
70
|
+
## Bundler Setup
|
|
71
|
+
|
|
72
|
+
The plugin loads its wasm with `new URL("./openjpegwasm.wasm", import.meta.url)`, which Vite and webpack 5 emit as an asset.
|
|
73
|
+
|
|
74
|
+
The codec's JavaScript only uses Node's `fs` and `path` in Node, but webpack 5 tries to bundle them, so turn them off:
|
|
75
|
+
|
|
76
|
+
```js
|
|
77
|
+
// webpack.config.js
|
|
78
|
+
export default {
|
|
79
|
+
resolve: { fallback: { fs: false, path: false } },
|
|
80
|
+
};
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Vite 7 and earlier pre-bundle the plugin away from its wasm in the dev server, which fails with `Failed to load the JPEG 2000 codec's wasm`.
|
|
84
|
+
Exclude it from pre-bundling, and include its CommonJS dependencies instead:
|
|
85
|
+
|
|
86
|
+
```js
|
|
87
|
+
// vite.config.js
|
|
88
|
+
export default {
|
|
89
|
+
optimizeDeps: {
|
|
90
|
+
exclude: ["@jimp/wasm-jpeg2000"],
|
|
91
|
+
include: [
|
|
92
|
+
"@jimp/wasm-jpeg2000 > @cornerstonejs/codec-openjpeg/wasmjs",
|
|
93
|
+
"@jimp/wasm-jpeg2000 > buffer",
|
|
94
|
+
],
|
|
95
|
+
},
|
|
96
|
+
};
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
For bundlers that don't handle `new URL` (like esbuild), serve `@cornerstonejs/codec-openjpeg/dist/openjpegwasm.wasm` yourself, then compile it and pass it in:
|
|
100
|
+
|
|
101
|
+
```ts
|
|
102
|
+
const codec = await WebAssembly.compileStreaming(
|
|
103
|
+
fetch("/assets/openjpegwasm.wasm"),
|
|
104
|
+
);
|
|
105
|
+
const Jimp = createJimp({
|
|
106
|
+
formats: [...defaultFormats, () => jpeg2000({ wasm: { codec } })],
|
|
107
|
+
});
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
## License
|
|
111
|
+
|
|
112
|
+
The browser build includes OpenJPEG's wasm, which is under the BSD 2-Clause License. See [OPENJPEG-LICENSE](./OPENJPEG-LICENSE).
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { Buffer } from "buffer";
|
|
2
|
+
export interface Component {
|
|
3
|
+
/** Bits per sample */
|
|
4
|
+
precision: number;
|
|
5
|
+
signed: boolean;
|
|
6
|
+
/** Horizontal subsampling */
|
|
7
|
+
dx: number;
|
|
8
|
+
/** Vertical subsampling */
|
|
9
|
+
dy: number;
|
|
10
|
+
}
|
|
11
|
+
export interface CodestreamHeader {
|
|
12
|
+
width: number;
|
|
13
|
+
height: number;
|
|
14
|
+
components: Component[];
|
|
15
|
+
/** Wavelet decomposition levels, the most a decoder can reduce by */
|
|
16
|
+
decompositions: number;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Reads the image size, components and decomposition levels from the main
|
|
20
|
+
* header of the codestream. Returns undefined if it can't be read.
|
|
21
|
+
*/
|
|
22
|
+
export declare function readCodestreamHeader(data: Buffer): CodestreamHeader | undefined;
|
|
23
|
+
/**
|
|
24
|
+
* Wraps an 8-bit RGB codestream in the boxes of a JP2 file: the signature,
|
|
25
|
+
* file type, JP2 header (image header and sRGB colour specification) and
|
|
26
|
+
* codestream boxes.
|
|
27
|
+
*/
|
|
28
|
+
export declare function writeJp2(codestream: Buffer, width: number, height: number): Buffer<ArrayBuffer>;
|
|
29
|
+
//# sourceMappingURL=codestream.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"codestream.d.ts","sourceRoot":"","sources":["../../src/codestream.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAgBhC,MAAM,WAAW,SAAS;IACxB,sBAAsB;IACtB,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,OAAO,CAAC;IAChB,6BAA6B;IAC7B,EAAE,EAAE,MAAM,CAAC;IACX,2BAA2B;IAC3B,EAAE,EAAE,MAAM,CAAC;CACZ;AAED,MAAM,WAAW,gBAAgB;IAC/B,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,SAAS,EAAE,CAAC;IACxB,qEAAqE;IACrE,cAAc,EAAE,MAAM,CAAC;CACxB;AAyCD;;;GAGG;AACH,wBAAgB,oBAAoB,CAClC,IAAI,EAAE,MAAM,GACX,gBAAgB,GAAG,SAAS,CA0D9B;AAYD;;;;GAIG;AACH,wBAAgB,QAAQ,CAAC,UAAU,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,uBAwBzE"}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { Buffer } from "buffer";
|
|
2
|
+
/** The signature box JP2 and JPX files start with */
|
|
3
|
+
const JP2_SIGNATURE = Buffer.from([
|
|
4
|
+
0x00, 0x00, 0x00, 0x0c, 0x6a, 0x50, 0x20, 0x20, 0x0d, 0x0a, 0x87, 0x0a,
|
|
5
|
+
]);
|
|
6
|
+
/** Codestream markers */
|
|
7
|
+
const SOC = 0xff4f;
|
|
8
|
+
const SIZ = 0xff51;
|
|
9
|
+
const COD = 0xff52;
|
|
10
|
+
const SOT = 0xff90;
|
|
11
|
+
/** Enumerated colour spaces of the JP2 colour specification box */
|
|
12
|
+
const SRGB = 16;
|
|
13
|
+
/** Finds the codestream of a JP2 or JPX file, or a raw codestream */
|
|
14
|
+
function findCodestream(data) {
|
|
15
|
+
if (data.readUInt16BE(0) === SOC) {
|
|
16
|
+
return data;
|
|
17
|
+
}
|
|
18
|
+
if (!data.subarray(0, 12).equals(JP2_SIGNATURE)) {
|
|
19
|
+
return undefined;
|
|
20
|
+
}
|
|
21
|
+
let offset = 0;
|
|
22
|
+
while (offset + 8 <= data.length) {
|
|
23
|
+
let length = data.readUInt32BE(offset);
|
|
24
|
+
let headerLength = 8;
|
|
25
|
+
if (length === 1 && offset + 16 <= data.length) {
|
|
26
|
+
// A 64-bit length follows the type
|
|
27
|
+
length = Number(data.readBigUInt64BE(offset + 8));
|
|
28
|
+
headerLength = 16;
|
|
29
|
+
}
|
|
30
|
+
else if (length === 0) {
|
|
31
|
+
// The last box can run to the end of the file
|
|
32
|
+
length = data.length - offset;
|
|
33
|
+
}
|
|
34
|
+
if (length < headerLength) {
|
|
35
|
+
return undefined;
|
|
36
|
+
}
|
|
37
|
+
if (data.toString("latin1", offset + 4, offset + 8) === "jp2c") {
|
|
38
|
+
return data.subarray(offset + headerLength, offset + length);
|
|
39
|
+
}
|
|
40
|
+
offset += length;
|
|
41
|
+
}
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Reads the image size, components and decomposition levels from the main
|
|
46
|
+
* header of the codestream. Returns undefined if it can't be read.
|
|
47
|
+
*/
|
|
48
|
+
export function readCodestreamHeader(data) {
|
|
49
|
+
try {
|
|
50
|
+
const codestream = findCodestream(data);
|
|
51
|
+
if (!codestream) {
|
|
52
|
+
return undefined;
|
|
53
|
+
}
|
|
54
|
+
let header = {};
|
|
55
|
+
// Skip SOC. Each marker segment is the marker, then its length including
|
|
56
|
+
// the length's 2 bytes.
|
|
57
|
+
let offset = 2;
|
|
58
|
+
while (offset + 4 <= codestream.length) {
|
|
59
|
+
const marker = codestream.readUInt16BE(offset);
|
|
60
|
+
if (marker === SOT) {
|
|
61
|
+
break;
|
|
62
|
+
}
|
|
63
|
+
if (marker === SIZ) {
|
|
64
|
+
const width = codestream.readUInt32BE(offset + 6) -
|
|
65
|
+
codestream.readUInt32BE(offset + 14);
|
|
66
|
+
const height = codestream.readUInt32BE(offset + 10) -
|
|
67
|
+
codestream.readUInt32BE(offset + 18);
|
|
68
|
+
const count = codestream.readUInt16BE(offset + 38);
|
|
69
|
+
const components = [];
|
|
70
|
+
for (let i = 0; i < count; i++) {
|
|
71
|
+
const ssiz = codestream[offset + 40 + i * 3];
|
|
72
|
+
components.push({
|
|
73
|
+
precision: (ssiz & 0x7f) + 1,
|
|
74
|
+
signed: (ssiz & 0x80) !== 0,
|
|
75
|
+
dx: codestream[offset + 41 + i * 3],
|
|
76
|
+
dy: codestream[offset + 42 + i * 3],
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
header = { ...header, width, height, components };
|
|
80
|
+
}
|
|
81
|
+
else if (marker === COD) {
|
|
82
|
+
// After Scod, the progression order, layer count and MCT
|
|
83
|
+
header.decompositions = codestream[offset + 9];
|
|
84
|
+
}
|
|
85
|
+
offset += 2 + codestream.readUInt16BE(offset + 2);
|
|
86
|
+
}
|
|
87
|
+
const { width, height, components, decompositions } = header;
|
|
88
|
+
return width && height && components && decompositions !== undefined
|
|
89
|
+
? { width, height, components, decompositions }
|
|
90
|
+
: undefined;
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
return undefined;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
function box(type, ...contents) {
|
|
97
|
+
const data = Buffer.concat(contents);
|
|
98
|
+
const header = Buffer.alloc(8);
|
|
99
|
+
header.writeUInt32BE(data.length + 8, 0);
|
|
100
|
+
header.write(type, 4, "latin1");
|
|
101
|
+
return Buffer.concat([header, data]);
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Wraps an 8-bit RGB codestream in the boxes of a JP2 file: the signature,
|
|
105
|
+
* file type, JP2 header (image header and sRGB colour specification) and
|
|
106
|
+
* codestream boxes.
|
|
107
|
+
*/
|
|
108
|
+
export function writeJp2(codestream, width, height) {
|
|
109
|
+
const brand = Buffer.from("jp2 \0\0\0\0jp2 ", "latin1");
|
|
110
|
+
const ihdr = Buffer.alloc(14);
|
|
111
|
+
ihdr.writeUInt32BE(height, 0);
|
|
112
|
+
ihdr.writeUInt32BE(width, 4);
|
|
113
|
+
ihdr.writeUInt16BE(3, 8);
|
|
114
|
+
// 8 bits per component, stored minus one
|
|
115
|
+
ihdr[10] = 7;
|
|
116
|
+
// Compressed with JPEG 2000
|
|
117
|
+
ihdr[11] = 7;
|
|
118
|
+
const colr = Buffer.alloc(7);
|
|
119
|
+
// Enumerated colour space
|
|
120
|
+
colr[0] = 1;
|
|
121
|
+
colr.writeUInt32BE(SRGB, 3);
|
|
122
|
+
return Buffer.concat([
|
|
123
|
+
JP2_SIGNATURE,
|
|
124
|
+
box("ftyp", brand),
|
|
125
|
+
box("jp2h", box("ihdr", ihdr), box("colr", colr)),
|
|
126
|
+
box("jp2c", codestream),
|
|
127
|
+
]);
|
|
128
|
+
}
|
|
129
|
+
//# sourceMappingURL=codestream.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"codestream.js","sourceRoot":"","sources":["../../src/codestream.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC,qDAAqD;AACrD,MAAM,aAAa,GAAG,MAAM,CAAC,IAAI,CAAC;IAChC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI;CACvE,CAAC,CAAC;AAEH,yBAAyB;AACzB,MAAM,GAAG,GAAG,MAAM,CAAC;AACnB,MAAM,GAAG,GAAG,MAAM,CAAC;AACnB,MAAM,GAAG,GAAG,MAAM,CAAC;AACnB,MAAM,GAAG,GAAG,MAAM,CAAC;AAEnB,mEAAmE;AACnE,MAAM,IAAI,GAAG,EAAE,CAAC;AAoBhB,qEAAqE;AACrE,SAAS,cAAc,CAAC,IAAY;IAClC,IAAI,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE,CAAC;QACjC,OAAO,IAAI,CAAC;IACd,CAAC;IAED,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,MAAM,CAAC,aAAa,CAAC,EAAE,CAAC;QAChD,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,IAAI,MAAM,GAAG,CAAC,CAAC;IAEf,OAAO,MAAM,GAAG,CAAC,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;QACjC,IAAI,MAAM,GAAG,IAAI,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC;QACvC,IAAI,YAAY,GAAG,CAAC,CAAC;QAErB,IAAI,MAAM,KAAK,CAAC,IAAI,MAAM,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EAAE,CAAC,GAAG,CAAC,CAAC;IACb,4BAA4B;IAC5B,IAAI,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC;IAEb,MAAM,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IAE7B,0BAA0B;IAC1B,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;IACZ,IAAI,CAAC,aAAa,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;IAE5B,OAAO,MAAM,CAAC,MAAM,CAAC;QACnB,aAAa;QACb,GAAG,CAAC,MAAM,EAAE,KAAK,CAAC;QAClB,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,IAAI,CAAC,EAAE,GAAG,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;QACjD,GAAG,CAAC,MAAM,EAAE,UAAU,CAAC;KACxB,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { Buffer } from \"buffer\";\n\n/** The signature box JP2 and JPX files start with */\nconst JP2_SIGNATURE = Buffer.from([\n 0x00, 0x00, 0x00, 0x0c, 0x6a, 0x50, 0x20, 0x20, 0x0d, 0x0a, 0x87, 0x0a,\n]);\n\n/** Codestream markers */\nconst SOC = 0xff4f;\nconst SIZ = 0xff51;\nconst COD = 0xff52;\nconst SOT = 0xff90;\n\n/** Enumerated colour spaces of the JP2 colour specification box */\nconst SRGB = 16;\n\nexport interface Component {\n /** Bits per sample */\n precision: number;\n signed: boolean;\n /** Horizontal subsampling */\n dx: number;\n /** Vertical subsampling */\n dy: number;\n}\n\nexport interface CodestreamHeader {\n width: number;\n height: number;\n components: Component[];\n /** Wavelet decomposition levels, the most a decoder can reduce by */\n decompositions: number;\n}\n\n/** Finds the codestream of a JP2 or JPX file, or a raw codestream */\nfunction findCodestream(data: Buffer) {\n if (data.readUInt16BE(0) === SOC) {\n return data;\n }\n\n if (!data.subarray(0, 12).equals(JP2_SIGNATURE)) {\n return undefined;\n }\n\n let offset = 0;\n\n while (offset + 8 <= data.length) {\n let length = data.readUInt32BE(offset);\n let headerLength = 8;\n\n if (length === 1 && offset + 16 <= data.length) {\n // A 64-bit length follows the type\n length = Number(data.readBigUInt64BE(offset + 8));\n headerLength = 16;\n } else if (length === 0) {\n // The last box can run to the end of the file\n length = data.length - offset;\n }\n\n if (length < headerLength) {\n return undefined;\n }\n\n if (data.toString(\"latin1\", offset + 4, offset + 8) === \"jp2c\") {\n return data.subarray(offset + headerLength, offset + length);\n }\n\n offset += length;\n }\n\n return undefined;\n}\n\n/**\n * Reads the image size, components and decomposition levels from the main\n * header of the codestream. Returns undefined if it can't be read.\n */\nexport function readCodestreamHeader(\n data: Buffer,\n): CodestreamHeader | undefined {\n try {\n const codestream = findCodestream(data);\n\n if (!codestream) {\n return undefined;\n }\n\n let header: Partial<CodestreamHeader> = {};\n // Skip SOC. Each marker segment is the marker, then its length including\n // the length's 2 bytes.\n let offset = 2;\n\n while (offset + 4 <= codestream.length) {\n const marker = codestream.readUInt16BE(offset);\n\n if (marker === SOT) {\n break;\n }\n\n if (marker === SIZ) {\n const width =\n codestream.readUInt32BE(offset + 6) -\n codestream.readUInt32BE(offset + 14);\n const height =\n codestream.readUInt32BE(offset + 10) -\n codestream.readUInt32BE(offset + 18);\n const count = codestream.readUInt16BE(offset + 38);\n const components: Component[] = [];\n\n for (let i = 0; i < count; i++) {\n const ssiz = codestream[offset + 40 + i * 3]!;\n\n components.push({\n precision: (ssiz & 0x7f) + 1,\n signed: (ssiz & 0x80) !== 0,\n dx: codestream[offset + 41 + i * 3]!,\n dy: codestream[offset + 42 + i * 3]!,\n });\n }\n\n header = { ...header, width, height, components };\n } else if (marker === COD) {\n // After Scod, the progression order, layer count and MCT\n header.decompositions = codestream[offset + 9];\n }\n\n offset += 2 + codestream.readUInt16BE(offset + 2);\n }\n\n const { width, height, components, decompositions } = header;\n\n return width && height && components && decompositions !== undefined\n ? { width, height, components, decompositions }\n : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction box(type: string, ...contents: Buffer[]) {\n const data = Buffer.concat(contents);\n const header = Buffer.alloc(8);\n\n header.writeUInt32BE(data.length + 8, 0);\n header.write(type, 4, \"latin1\");\n\n return Buffer.concat([header, data]);\n}\n\n/**\n * Wraps an 8-bit RGB codestream in the boxes of a JP2 file: the signature,\n * file type, JP2 header (image header and sRGB colour specification) and\n * codestream boxes.\n */\nexport function writeJp2(codestream: Buffer, width: number, height: number) {\n const brand = Buffer.from(\"jp2 \\0\\0\\0\\0jp2 \", \"latin1\");\n const ihdr = Buffer.alloc(14);\n\n ihdr.writeUInt32BE(height, 0);\n ihdr.writeUInt32BE(width, 4);\n ihdr.writeUInt16BE(3, 8);\n // 8 bits per component, stored minus one\n ihdr[10] = 7;\n // Compressed with JPEG 2000\n ihdr[11] = 7;\n\n const colr = Buffer.alloc(7);\n\n // Enumerated colour space\n colr[0] = 1;\n colr.writeUInt32BE(SRGB, 3);\n\n return Buffer.concat([\n JP2_SIGNATURE,\n box(\"ftyp\", brand),\n box(\"jp2h\", box(\"ihdr\", ihdr), box(\"colr\", colr)),\n box(\"jp2c\", codestream),\n ]);\n}\n"]}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { Buffer } from "buffer";
|
|
2
|
+
import { Bitmap } from "@jimp/types";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
declare const Jpeg2000OptionsSchema: z.ZodObject<{
|
|
5
|
+
compressionRatio: z.ZodDefault<z.ZodOptional<z.ZodNumber>>;
|
|
6
|
+
decompositions: z.ZodDefault<z.ZodOptional<z.ZodNumber>>;
|
|
7
|
+
}, z.core.$strict>;
|
|
8
|
+
type Jpeg2000Options = z.infer<typeof Jpeg2000OptionsSchema>;
|
|
9
|
+
export interface DecodeJpeg2000Options {
|
|
10
|
+
/**
|
|
11
|
+
* Decode at a lower resolution. Each step halves the width and height
|
|
12
|
+
* (rounding up), down to the image's smallest resolution. It's much faster
|
|
13
|
+
* and uses less memory than decoding a huge image in full and resizing it.
|
|
14
|
+
* @default 0
|
|
15
|
+
*/
|
|
16
|
+
reduce?: number;
|
|
17
|
+
/**
|
|
18
|
+
* Decode only the first quality layers of an image encoded with several,
|
|
19
|
+
* for a quick lower quality preview. 0 decodes all of them.
|
|
20
|
+
* @default 0
|
|
21
|
+
*/
|
|
22
|
+
layers?: number;
|
|
23
|
+
/**
|
|
24
|
+
* Largest image, in megapixels, that will be decoded, after `reduce`.
|
|
25
|
+
* Larger images are rejected before any pixel memory is allocated.
|
|
26
|
+
* @default 100
|
|
27
|
+
*/
|
|
28
|
+
maxResolutionInMP?: number;
|
|
29
|
+
}
|
|
30
|
+
export interface Jpeg2000Wasm {
|
|
31
|
+
/** The compiled `@cornerstonejs/codec-openjpeg/wasm` */
|
|
32
|
+
codec?: WebAssembly.Module;
|
|
33
|
+
}
|
|
34
|
+
export interface Jpeg2000FormatOptions {
|
|
35
|
+
/**
|
|
36
|
+
* A precompiled wasm module for runtimes or bundlers where the plugin
|
|
37
|
+
* can't load the codec's wasm itself.
|
|
38
|
+
* The codec is initialized once, by the first instance that encodes or
|
|
39
|
+
* decodes, so pass the same module to every instance.
|
|
40
|
+
*/
|
|
41
|
+
wasm?: Jpeg2000Wasm;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* JP2 files, the usual JPEG 2000 container (.jp2).
|
|
45
|
+
* Images are written as 8-bit sRGB without alpha.
|
|
46
|
+
*/
|
|
47
|
+
export default function jpeg2000({ wasm }?: Jpeg2000FormatOptions): {
|
|
48
|
+
mime: "image/jp2";
|
|
49
|
+
hasAlpha: false;
|
|
50
|
+
encode: (bitmap: Bitmap, options?: Partial<Jpeg2000Options>) => Promise<Buffer<ArrayBuffer>>;
|
|
51
|
+
decode: (data: Buffer<ArrayBufferLike>, options?: DecodeJpeg2000Options) => Promise<Bitmap>;
|
|
52
|
+
};
|
|
53
|
+
/** Raw JPEG 2000 codestreams, without a container (.j2c, .j2k) */
|
|
54
|
+
export declare function j2c({ wasm }?: Jpeg2000FormatOptions): {
|
|
55
|
+
mime: "image/j2c";
|
|
56
|
+
hasAlpha: false;
|
|
57
|
+
encode: (bitmap: Bitmap, options?: Partial<Jpeg2000Options>) => Promise<Buffer<ArrayBuffer>>;
|
|
58
|
+
decode: (data: Buffer<ArrayBufferLike>, options?: DecodeJpeg2000Options) => Promise<Bitmap>;
|
|
59
|
+
};
|
|
60
|
+
/**
|
|
61
|
+
* JPX files (.jpx, .jpf), the extended JPEG 2000 container. Only decoding is
|
|
62
|
+
* supported, of the codestreams that only use JPEG 2000 part 1 features.
|
|
63
|
+
*/
|
|
64
|
+
export declare function jpx({ wasm }?: Jpeg2000FormatOptions): {
|
|
65
|
+
mime: "image/jpx";
|
|
66
|
+
hasAlpha: false;
|
|
67
|
+
encode: () => Promise<never>;
|
|
68
|
+
decode: (data: Buffer<ArrayBufferLike>, options?: DecodeJpeg2000Options) => Promise<Bitmap>;
|
|
69
|
+
};
|
|
70
|
+
export {};
|
|
71
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAIhC,OAAO,EAAE,MAAM,EAAU,MAAM,aAAa,CAAC;AAC7C,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AASxB,QAAA,MAAM,qBAAqB;;;kBAkBhB,CAAC;AAEZ,KAAK,eAAe,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,qBAAqB,CAAC,CAAC;AAE7D,MAAM,WAAW,qBAAqB;IACpC;;;;;OAKG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;;OAIG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;;OAIG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED,MAAM,WAAW,YAAY;IAC3B,wDAAwD;IACxD,KAAK,CAAC,EAAE,WAAW,CAAC,MAAM,CAAC;CAC5B;AAED,MAAM,WAAW,qBAAqB;IACpC;;;;;OAKG;IACH,IAAI,CAAC,EAAE,YAAY,CAAC;CACrB;AAsPD;;;GAGG;AACH,MAAM,CAAC,OAAO,UAAU,QAAQ,CAAC,EAAE,IAAI,EAAE,GAAE,qBAA0B;;;uCAIjC,OAAO,CAAC,eAAe,CAAC;sDAMhC,qBAAqB;EAGhD;AAED,kEAAkE;AAClE,wBAAgB,GAAG,CAAC,EAAE,IAAI,EAAE,GAAE,qBAA0B;;;uCAI1B,OAAO,CAAC,eAAe,CAAC;sDAE1B,qBAAqB;EAGhD;AAED;;;GAGG;AACH,wBAAgB,GAAG,CAAC,EAAE,IAAI,EAAE,GAAE,qBAA0B;;;;sDAS5B,qBAAqB;EAGhD"}
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import { Buffer } from "buffer";
|
|
2
|
+
import OpenJPEGWASM from "@cornerstonejs/codec-openjpeg/wasmjs";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { readCodestreamHeader, writeJp2, } from "./codestream.js";
|
|
5
|
+
import { loadWasm } from "./load-wasm.js";
|
|
6
|
+
const Jpeg2000OptionsSchema = z
|
|
7
|
+
.object({
|
|
8
|
+
/**
|
|
9
|
+
* How many times smaller than the uncompressed RGB pixels the file
|
|
10
|
+
* should be, e.g. 20 for 20:1. 1 is lossless: it uses the reversible
|
|
11
|
+
* wavelet and keeps every pixel exactly. Above 1, the irreversible
|
|
12
|
+
* wavelet is used and quality drops as the ratio rises.
|
|
13
|
+
* @default 1
|
|
14
|
+
*/
|
|
15
|
+
compressionRatio: z.number().optional().default(1),
|
|
16
|
+
/**
|
|
17
|
+
* Wavelet decomposition levels. Each level is a resolution, half the
|
|
18
|
+
* size of the one above, that decoders can `reduce` to without decoding
|
|
19
|
+
* the full image. Limited to what the image's size allows.
|
|
20
|
+
* @default 5
|
|
21
|
+
*/
|
|
22
|
+
decompositions: z.number().optional().default(5),
|
|
23
|
+
})
|
|
24
|
+
.strict();
|
|
25
|
+
let codecReady;
|
|
26
|
+
/** What OpenJPEG printed during the current encode or decode */
|
|
27
|
+
let messages = [];
|
|
28
|
+
function initCodecOnce(module) {
|
|
29
|
+
codecReady ??= Promise.resolve(module ?? loadWasm()).then((wasm) => new Promise((resolve, reject) => {
|
|
30
|
+
OpenJPEGWASM({
|
|
31
|
+
// OpenJPEG logs its errors, warnings and progress
|
|
32
|
+
print: (message) => messages.push(message),
|
|
33
|
+
printErr: (message) => messages.push(message),
|
|
34
|
+
instantiateWasm(imports, receiveInstance) {
|
|
35
|
+
WebAssembly.instantiate(wasm, imports).then((instance) => receiveInstance(instance, wasm), reject);
|
|
36
|
+
return {};
|
|
37
|
+
},
|
|
38
|
+
}).then(resolve, reject);
|
|
39
|
+
}));
|
|
40
|
+
return codecReady;
|
|
41
|
+
}
|
|
42
|
+
/** The errors OpenJPEG printed, to explain why it failed */
|
|
43
|
+
function withErrors(message) {
|
|
44
|
+
const errors = messages
|
|
45
|
+
.filter((line) => line.startsWith("[ERROR]"))
|
|
46
|
+
.map((line) => line.slice("[ERROR]".length).trim());
|
|
47
|
+
return new Error(errors.length ? `${message}: ${errors.join(". ")}` : message);
|
|
48
|
+
}
|
|
49
|
+
/** Rejects layouts the codec can't decode, or decodes to the wrong pixels */
|
|
50
|
+
function validate({ components }) {
|
|
51
|
+
const [first, cb, cr] = components;
|
|
52
|
+
if (!first ||
|
|
53
|
+
components.some(({ precision, signed }) => precision !== first.precision || signed !== first.signed)) {
|
|
54
|
+
throw new Error("Unsupported JPEG 2000 image: every component must have the same bit depth");
|
|
55
|
+
}
|
|
56
|
+
if (first.precision > 16) {
|
|
57
|
+
throw new Error(`Unsupported JPEG 2000 bit depth ${first.precision}: up to 16 bits per sample can be decoded`);
|
|
58
|
+
}
|
|
59
|
+
// The codec clamps them to 0-255, losing the negative half
|
|
60
|
+
if (components.length === 1 && first.signed && first.precision <= 8) {
|
|
61
|
+
throw new Error("Unsupported JPEG 2000 image: signed grayscale samples of 8 bits or fewer");
|
|
62
|
+
}
|
|
63
|
+
const subsampled = components.some(({ dx, dy }) => dx !== 1 || dy !== 1);
|
|
64
|
+
// The codec converts YCbCr with 4:2:0 or 4:2:2 chroma to RGB
|
|
65
|
+
const subsampledChroma = components.length === 3 &&
|
|
66
|
+
first.dx === 1 &&
|
|
67
|
+
first.dy === 1 &&
|
|
68
|
+
cb.dx === 2 &&
|
|
69
|
+
cr.dx === 2 &&
|
|
70
|
+
cb.dy === cr.dy &&
|
|
71
|
+
cb.dy <= 2;
|
|
72
|
+
if (subsampled && !subsampledChroma) {
|
|
73
|
+
throw new Error("Unsupported JPEG 2000 subsampling: only the chroma of YCbCr 4:2:0 and 4:2:2 images can be subsampled");
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
/** Converts the codec's interleaved gray or RGB samples to 8-bit RGBA */
|
|
77
|
+
function toRgba(samples, pixels, components, bitsPerSample, signed) {
|
|
78
|
+
// Copy the samples out of wasm memory, which also aligns 16-bit ones
|
|
79
|
+
const copy = samples.slice();
|
|
80
|
+
const values = bitsPerSample > 8
|
|
81
|
+
? signed
|
|
82
|
+
? new Int16Array(copy.buffer)
|
|
83
|
+
: new Uint16Array(copy.buffer)
|
|
84
|
+
: signed
|
|
85
|
+
? new Int8Array(copy.buffer)
|
|
86
|
+
: copy;
|
|
87
|
+
const offset = signed ? 2 ** (bitsPerSample - 1) : 0;
|
|
88
|
+
const scale = 255 / (2 ** bitsPerSample - 1);
|
|
89
|
+
// Rounds and clamps to 0-255
|
|
90
|
+
const rgba = new Uint8ClampedArray(pixels * 4);
|
|
91
|
+
for (let i = 0; i < pixels; i++) {
|
|
92
|
+
for (let c = 0; c < 3; c++) {
|
|
93
|
+
const value = values[i * components + (components === 1 ? 0 : c)];
|
|
94
|
+
rgba[i * 4 + c] = (value + offset) * scale;
|
|
95
|
+
}
|
|
96
|
+
rgba[i * 4 + 3] = 255;
|
|
97
|
+
}
|
|
98
|
+
return Buffer.from(rgba.buffer);
|
|
99
|
+
}
|
|
100
|
+
async function decode(data, { reduce = 0, layers = 0, maxResolutionInMP = 100 }, wasm) {
|
|
101
|
+
const header = readCodestreamHeader(data);
|
|
102
|
+
if (!header) {
|
|
103
|
+
throw new Error("Invalid JPEG 2000 image: the codestream's main header can't be read");
|
|
104
|
+
}
|
|
105
|
+
validate(header);
|
|
106
|
+
const level = Math.min(Math.max(0, Math.floor(reduce)), header.decompositions);
|
|
107
|
+
const width = Math.ceil(header.width / 2 ** level);
|
|
108
|
+
const height = Math.ceil(header.height / 2 ** level);
|
|
109
|
+
if (width * height > maxResolutionInMP * 1_000_000) {
|
|
110
|
+
throw new Error(`JPEG 2000 dimensions ${width}x${height} exceed the maximum resolution of ${maxResolutionInMP} megapixels. Use the reduce option to decode it at a lower resolution.`);
|
|
111
|
+
}
|
|
112
|
+
const codec = await initCodecOnce(wasm);
|
|
113
|
+
const decoder = new codec.J2KDecoder();
|
|
114
|
+
messages = [];
|
|
115
|
+
try {
|
|
116
|
+
try {
|
|
117
|
+
decoder.getEncodedBuffer(data.length).set(data);
|
|
118
|
+
decoder.decodeSubResolution(level, Math.max(0, Math.floor(layers)));
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
// C++ exceptions reach JS as pointers, without their message
|
|
122
|
+
const count = header.components.length;
|
|
123
|
+
throw count === 1 || count === 3
|
|
124
|
+
? withErrors("Failed to decode the JPEG 2000 image")
|
|
125
|
+
: new Error(`Unsupported JPEG 2000 image with ${count} components: only grayscale and RGB images can be decoded, without alpha`);
|
|
126
|
+
}
|
|
127
|
+
const frame = decoder.getFrameInfo();
|
|
128
|
+
// Without an exception, OpenJPEG's own failures leave the frame empty
|
|
129
|
+
if (!frame.width) {
|
|
130
|
+
throw withErrors("Failed to decode the JPEG 2000 image");
|
|
131
|
+
}
|
|
132
|
+
const size = decoder.calculateSizeAtDecompositionLevel(level);
|
|
133
|
+
return {
|
|
134
|
+
data: toRgba(decoder.getDecodedBuffer(), size.width * size.height, frame.componentCount, frame.bitsPerSample, frame.isSigned),
|
|
135
|
+
width: size.width,
|
|
136
|
+
height: size.height,
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
finally {
|
|
140
|
+
decoder.delete();
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
/** Encodes the bitmap's RGB, without alpha, as a codestream */
|
|
144
|
+
async function encode({ width, height, data }, options, wasm) {
|
|
145
|
+
const { compressionRatio, decompositions } = Jpeg2000OptionsSchema.parse(options);
|
|
146
|
+
const codec = await initCodecOnce(wasm);
|
|
147
|
+
const encoder = new codec.J2KEncoder();
|
|
148
|
+
messages = [];
|
|
149
|
+
try {
|
|
150
|
+
const pixels = encoder.getDecodedBuffer({
|
|
151
|
+
width,
|
|
152
|
+
height,
|
|
153
|
+
bitsPerSample: 8,
|
|
154
|
+
componentCount: 3,
|
|
155
|
+
isSigned: false,
|
|
156
|
+
});
|
|
157
|
+
for (let i = 0; i < width * height; i++) {
|
|
158
|
+
pixels[i * 3] = data[i * 4];
|
|
159
|
+
pixels[i * 3 + 1] = data[i * 4 + 1];
|
|
160
|
+
pixels[i * 3 + 2] = data[i * 4 + 2];
|
|
161
|
+
}
|
|
162
|
+
// The smallest resolution needs at least a pixel in each direction
|
|
163
|
+
encoder.setDecompositions(Math.min(Math.max(0, Math.round(decompositions)), Math.floor(Math.log2(Math.min(width, height)))));
|
|
164
|
+
if (compressionRatio > 1) {
|
|
165
|
+
encoder.setQuality(false, 1);
|
|
166
|
+
encoder.setCompressionRatio(0, compressionRatio);
|
|
167
|
+
}
|
|
168
|
+
try {
|
|
169
|
+
encoder.encode();
|
|
170
|
+
}
|
|
171
|
+
catch {
|
|
172
|
+
throw withErrors("Failed to encode the JPEG 2000 image");
|
|
173
|
+
}
|
|
174
|
+
// Copied out of wasm memory
|
|
175
|
+
return Buffer.from(encoder.getEncodedBuffer());
|
|
176
|
+
}
|
|
177
|
+
finally {
|
|
178
|
+
encoder.delete();
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* JP2 files, the usual JPEG 2000 container (.jp2).
|
|
183
|
+
* Images are written as 8-bit sRGB without alpha.
|
|
184
|
+
*/
|
|
185
|
+
export default function jpeg2000({ wasm } = {}) {
|
|
186
|
+
return {
|
|
187
|
+
mime: "image/jp2",
|
|
188
|
+
hasAlpha: false,
|
|
189
|
+
encode: async (bitmap, options = {}) => writeJp2(await encode(bitmap, options, wasm?.codec), bitmap.width, bitmap.height),
|
|
190
|
+
decode: (data, options = {}) => decode(data, options, wasm?.codec),
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
/** Raw JPEG 2000 codestreams, without a container (.j2c, .j2k) */
|
|
194
|
+
export function j2c({ wasm } = {}) {
|
|
195
|
+
return {
|
|
196
|
+
mime: "image/j2c",
|
|
197
|
+
hasAlpha: false,
|
|
198
|
+
encode: (bitmap, options = {}) => encode(bitmap, options, wasm?.codec),
|
|
199
|
+
decode: (data, options = {}) => decode(data, options, wasm?.codec),
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* JPX files (.jpx, .jpf), the extended JPEG 2000 container. Only decoding is
|
|
204
|
+
* supported, of the codestreams that only use JPEG 2000 part 1 features.
|
|
205
|
+
*/
|
|
206
|
+
export function jpx({ wasm } = {}) {
|
|
207
|
+
return {
|
|
208
|
+
mime: "image/jpx",
|
|
209
|
+
hasAlpha: false,
|
|
210
|
+
encode: async () => {
|
|
211
|
+
throw new Error("Writing JPX isn't supported. Write a JP2 (image/jp2) instead, which JPX readers can read too.");
|
|
212
|
+
},
|
|
213
|
+
decode: (data, options = {}) => decode(data, options, wasm?.codec),
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
//# sourceMappingURL=index.js.map
|