imagepressor 0.1.0 → 0.2.1
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/README.md +87 -55
- package/dist/canvas.d.ts +1 -1
- package/dist/canvas.d.ts.map +1 -1
- package/dist/index.cjs +24 -32
- package/dist/index.cjs.map +9 -7
- package/dist/index.d.ts +6 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +24 -32
- package/dist/index.js.map +9 -7
- package/dist/jpeg.d.ts +22 -5
- package/dist/jpeg.d.ts.map +1 -1
- package/dist/types.d.ts +20 -6
- package/dist/types.d.ts.map +1 -1
- package/dist/utils.d.ts +27 -0
- package/dist/utils.d.ts.map +1 -0
- package/dist/webp.d.ts +38 -0
- package/dist/webp.d.ts.map +1 -0
- package/dist/worker.d.ts +1 -1
- package/dist/worker.d.ts.map +1 -1
- package/package.json +1 -1
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Jai
|
|
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/README.md
CHANGED
|
@@ -1,21 +1,32 @@
|
|
|
1
1
|
# imagepressor
|
|
2
2
|
|
|
3
|
-
> High-performance, zero-dependency, client-side image compression library that runs off the main thread in a Web Worker, preserving camera EXIF metadata and Display P3 color profiles.
|
|
3
|
+
> High-performance, zero-dependency, client-side image compression library that runs off the main thread in a Web Worker, preserving camera EXIF metadata and Display P3 color profiles across both JPEG and WebP.
|
|
4
4
|
|
|
5
|
-
[](https://ijaik.github.io/imagepressor/)
|
|
6
|
+
[](https://www.npmjs.com/package/imagepressor)
|
|
7
|
+
[](https://bundlephobia.com/package/imagepressor)
|
|
8
|
+
[](https://opensource.org/licenses/MIT)
|
|
9
|
+
|
|
10
|
+
🎮 **Interactive Live Playground**: [https://ijaik.github.io/imagepressor/](https://ijaik.github.io/imagepressor/)
|
|
7
11
|
|
|
8
12
|
---
|
|
9
13
|
|
|
10
14
|
## Highlights
|
|
11
15
|
|
|
12
|
-
- **Off-Main-Thread Processing:**
|
|
13
|
-
- **100% CSP-Safe & Offline
|
|
14
|
-
- **
|
|
15
|
-
- **Non-
|
|
16
|
-
- **
|
|
17
|
-
-
|
|
18
|
-
- **
|
|
16
|
+
- **Off-Main-Thread Processing:** Compresses and resizes images inside a dedicated Web Worker via `createImageBitmap` and `OffscreenCanvas`. The UI remains smooth and responsive at 60 fps, even during 4K or 30MB+ camera photo uploads.
|
|
17
|
+
- **100% CSP-Safe & Offline-Ready:** Uses a self-contained inline Web Worker without external CDN scripts (`blob:` worker), complying with strict Content Security Policies.
|
|
18
|
+
- **Bi-Directional EXIF & Display P3 Preservation (JPEG & WebP):**
|
|
19
|
+
- **JPEG:** Non-destructively preserves and re-injects raw APP1 (EXIF) and APP2 (ICC profile) segments.
|
|
20
|
+
- **WebP:** Built-in pure TypeScript WebP RIFF muxer upgrades simple VP8 bitstreams into extended `VP8X` containers with dedicated `EXIF` and `ICCP` chunks (no WASM, no Node APIs).
|
|
21
|
+
- Preserves camera make/model, focal length, ISO, shutter speed, and capture timestamps without washed-out colors on iPhones, MacBooks, and modern wide-gamut monitors.
|
|
22
|
+
- **Non-Destructive Orientation Normalization:** Normalizes EXIF orientation tags in place to `1` (Standard), preventing double-rotation issues in external viewers.
|
|
23
|
+
- **Zero-Memory Chunk-Hopping Inspector:** `getImageMetadata()` reads RIFF headers and hops past multi-megabyte image pixel frames directly to the metadata chunks, keeping memory footprint minimal.
|
|
24
|
+
- **Smart Anti-Expansion Guards & Strict Mode:**
|
|
25
|
+
- Prevents generational file bloat when re-compressing already-optimized images.
|
|
26
|
+
- Automatically guards against browser WebP 100% lossless mode (`VP8L`) inflation.
|
|
27
|
+
- Supports `strict: true` (following Compressor.js standards) to guarantee output is never larger than the input file.
|
|
28
|
+
- **Native Transparency via WebP:** Recommends modern WebP for transparent assets (logos, UI graphics), eliminating black backgrounds without lossless PNG bloat.
|
|
29
|
+
- **Zero Runtime Dependencies:** Pure TypeScript and native Web Platform APIs. ~6 KB min+gzip.
|
|
19
30
|
|
|
20
31
|
---
|
|
21
32
|
|
|
@@ -35,22 +46,25 @@ yarn add imagepressor
|
|
|
35
46
|
|
|
36
47
|
## Quick Start
|
|
37
48
|
|
|
38
|
-
Compress an image
|
|
49
|
+
Compress an image down to under 1 MB and max 1920px width:
|
|
39
50
|
|
|
40
51
|
```typescript
|
|
41
52
|
import { compressImage } from "imagepressor";
|
|
42
53
|
|
|
43
|
-
const fileInput = document.querySelector(
|
|
54
|
+
const fileInput = document.querySelector(
|
|
55
|
+
'input[type="file"]',
|
|
56
|
+
) as HTMLInputElement;
|
|
44
57
|
|
|
45
58
|
fileInput.addEventListener("change", async (event) => {
|
|
46
|
-
const
|
|
59
|
+
const target = event.target as HTMLInputElement;
|
|
60
|
+
const file = target.files?.[0];
|
|
47
61
|
if (!file) return;
|
|
48
62
|
|
|
49
63
|
try {
|
|
50
64
|
const compressed = await compressImage(file, {
|
|
51
|
-
maxSizeMB: 1,
|
|
52
|
-
maxWidth: 1920,
|
|
53
|
-
quality: 0.85,
|
|
65
|
+
maxSizeMB: 1, // Target maximum size: 1 MB
|
|
66
|
+
maxWidth: 1920, // Max width in pixels (aspect ratio maintained)
|
|
67
|
+
quality: 0.85, // Visual quality (0.0 to 1.0)
|
|
54
68
|
});
|
|
55
69
|
|
|
56
70
|
console.log("Original size:", file.size);
|
|
@@ -67,9 +81,21 @@ fileInput.addEventListener("change", async (event) => {
|
|
|
67
81
|
|
|
68
82
|
## Advanced Usage
|
|
69
83
|
|
|
70
|
-
### 1.
|
|
84
|
+
### 1. WebP Compression with EXIF & Transparency
|
|
71
85
|
|
|
72
|
-
|
|
86
|
+
WebP delivers ~25–40% smaller file sizes than JPEG while supporting full alpha transparency. `imagepressor` injects TIFF-compliant EXIF and ICC chunks directly into the WebP container:
|
|
87
|
+
|
|
88
|
+
```typescript
|
|
89
|
+
const webpFile = await compressImage(originalFile, {
|
|
90
|
+
mimeType: "image/webp",
|
|
91
|
+
quality: 0.85,
|
|
92
|
+
preserveMetadata: true, // Retains camera details & Display P3 ICC profile
|
|
93
|
+
});
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
### 2. Real-Time Progress Tracking
|
|
97
|
+
|
|
98
|
+
Keep users informed during multi-pass compression pipelines:
|
|
73
99
|
|
|
74
100
|
```typescript
|
|
75
101
|
const compressed = await compressImage(largeFile, {
|
|
@@ -82,14 +108,13 @@ const compressed = await compressImage(largeFile, {
|
|
|
82
108
|
});
|
|
83
109
|
```
|
|
84
110
|
|
|
85
|
-
###
|
|
111
|
+
### 3. Immediate Cancellation with AbortSignal
|
|
86
112
|
|
|
87
|
-
Cancel compression instantly if the user navigates away or
|
|
113
|
+
Cancel compression instantly if the user navigates away or clears the queue:
|
|
88
114
|
|
|
89
115
|
```typescript
|
|
90
116
|
const controller = new AbortController();
|
|
91
117
|
|
|
92
|
-
// Cancel button click handler
|
|
93
118
|
cancelButton.addEventListener("click", () => {
|
|
94
119
|
controller.abort();
|
|
95
120
|
});
|
|
@@ -99,8 +124,8 @@ try {
|
|
|
99
124
|
maxSizeMB: 1,
|
|
100
125
|
signal: controller.signal,
|
|
101
126
|
});
|
|
102
|
-
} catch (err) {
|
|
103
|
-
if (err.name === "AbortError") {
|
|
127
|
+
} catch (err: unknown) {
|
|
128
|
+
if (err instanceof DOMException && err.name === "AbortError") {
|
|
104
129
|
console.log("Compression cancelled by user.");
|
|
105
130
|
} else {
|
|
106
131
|
console.error("An unexpected error occurred:", err);
|
|
@@ -108,56 +133,63 @@ try {
|
|
|
108
133
|
}
|
|
109
134
|
```
|
|
110
135
|
|
|
111
|
-
###
|
|
136
|
+
### 4. Inspecting Image Metadata
|
|
112
137
|
|
|
113
|
-
|
|
138
|
+
Use the built-in parser to inspect camera hardware, orientation, and color profile from either JPEG or WebP files without decoding pixels:
|
|
114
139
|
|
|
115
140
|
```typescript
|
|
116
|
-
|
|
117
|
-
mimeType: "image/jpeg",
|
|
118
|
-
backgroundColor: "#f4f4f5", // Fill color for transparent pixels
|
|
119
|
-
quality: 0.88,
|
|
120
|
-
});
|
|
121
|
-
```
|
|
122
|
-
|
|
123
|
-
### 4. Direct Blob and Camera Input
|
|
141
|
+
import { getImageMetadata } from "imagepressor";
|
|
124
142
|
|
|
125
|
-
|
|
143
|
+
const metadata = await getImageMetadata(file);
|
|
126
144
|
|
|
127
|
-
|
|
128
|
-
//
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
145
|
+
console.log(metadata.hasExif); // true
|
|
146
|
+
console.log(metadata.make); // "Apple"
|
|
147
|
+
console.log(metadata.model); // "iPhone 15 Pro"
|
|
148
|
+
console.log(metadata.dateTime); // "2024:05:12 14:23:01"
|
|
149
|
+
console.log(metadata.colorSpace); // "ICC profile embedded" (or "sRGB (Standard)")
|
|
150
|
+
console.log(metadata.orientation); // 1
|
|
133
151
|
```
|
|
134
152
|
|
|
135
153
|
---
|
|
136
154
|
|
|
137
155
|
## Options API Reference
|
|
138
156
|
|
|
139
|
-
| Option
|
|
140
|
-
|
|
|
141
|
-
| `maxSizeMB`
|
|
142
|
-
| `maxWidth`
|
|
143
|
-
| `maxHeight`
|
|
144
|
-
| `quality`
|
|
145
|
-
| `mimeType`
|
|
146
|
-
| `preserveMetadata
|
|
147
|
-
| `
|
|
148
|
-
| `useWebWorker`
|
|
149
|
-
| `signal`
|
|
150
|
-
| `onProgress`
|
|
157
|
+
| Option | Type | Default | Description |
|
|
158
|
+
| :----------------- | :------------------------------------------ | :------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
159
|
+
| `maxSizeMB` | `number` | `undefined` | Target maximum output file size in megabytes (e.g. `1` for 1 MB). If omitted, compression is governed by `quality` and dimensions without forcing a hard megabyte ceiling. |
|
|
160
|
+
| `maxWidth` | `number` | `undefined` | Maximum width in pixels. Proportional scaling preserves aspect ratio. |
|
|
161
|
+
| `maxHeight` | `number` | `undefined` | Maximum height in pixels. Proportional scaling preserves aspect ratio. |
|
|
162
|
+
| `quality` | `number` | `0.85` | Compression quality between `0.0` (lowest, smallest) and `1.0` (highest, largest). |
|
|
163
|
+
| `mimeType` | `"image/jpeg" \| "image/webp"` | input type | Target output format (`"image/jpeg"`, `"image/webp"`). Defaults to input MIME type (WebP/PNG $\rightarrow$ WebP, JPEG $\rightarrow$ JPEG). |
|
|
164
|
+
| `preserveMetadata` | `boolean` | `true` | When `true`, extracts and re-injects camera EXIF and the embedded ICC color profile for both JPEG and WebP outputs. Best-effort: corrupt metadata never fails a compression. |
|
|
165
|
+
| `strict` | `boolean` | `true` (same format) | When `true`, returns the original image if compression output turns out larger than the original image without dimension downscaling. Ignored when `maxSizeMB` is set: the smallest attempt is returned so the requested ceiling wins. |
|
|
166
|
+
| `useWebWorker` | `boolean` | `true` | Runs off the main thread in an inline Web Worker. Automatically falls back to main-thread processing if workers or `OffscreenCanvas` are unavailable. |
|
|
167
|
+
| `signal` | `AbortSignal` | `undefined` | An `AbortSignal` to cancel compression immediately and clean up worker memory. |
|
|
168
|
+
| `onProgress` | `(progress: number, stage: string) => void` | `undefined` | Callback receiving `(percent: number, stage: string)`. |
|
|
169
|
+
|
|
170
|
+
---
|
|
171
|
+
|
|
172
|
+
## Exported Utilities
|
|
173
|
+
|
|
174
|
+
| Function | Description |
|
|
175
|
+
| :------------------------------------------------- | :----------------------------------------------------------------------------------------- |
|
|
176
|
+
| `compressImage(fileOrBlob, options)` | Primary client-side compression function with worker offloading and metadata preservation. |
|
|
177
|
+
| `getImageMetadata(blob)` | Fast zero-memory metadata scanner for JPEG APP1/APP2 markers and WebP RIFF chunks. |
|
|
178
|
+
| `extractMetadataSegments(blob)` | Extracts raw binary metadata segments (EXIF APP1 and ICC APP2) from JPEG or WebP files. |
|
|
179
|
+
| `spliceMetadataIntoBlob(blob, segments)` | Injects binary metadata segments into a JPEG blob. |
|
|
180
|
+
| `spliceWebpMetadata(blob, segments, w, h)` | Muxes binary metadata segments into an extended WebP container. |
|
|
181
|
+
| `insertWebPExif(webpBytes, rawExif, rawIcc, w, h)` | Low-level pure TypeScript WebP RIFF muxer that upgrades simple VP8 WebP to extended VP8X. |
|
|
182
|
+
| `normalizeExifOrientation(segment)` | Normalizes EXIF orientation tag in-place to `1` (Standard). |
|
|
151
183
|
|
|
152
184
|
---
|
|
153
185
|
|
|
154
186
|
## Browser Support
|
|
155
187
|
|
|
156
|
-
`
|
|
188
|
+
`imagepressor` is tested across all modern web browsers:
|
|
157
189
|
|
|
158
|
-
- **Chrome / Edge / Chromium:** 69+
|
|
190
|
+
- **Chrome / Edge / Chromium:** 69+ (full Web Worker + `OffscreenCanvas` support)
|
|
159
191
|
- **Firefox:** 105+
|
|
160
|
-
- **Safari / iOS Safari:** 16.4+ (falls back
|
|
192
|
+
- **Safari / iOS Safari:** 16.4+ (transparently falls back to main-thread canvas on older iOS Safari)
|
|
161
193
|
- **Node.js / SSR:** Safely passes through input files without crashing during server-side rendering.
|
|
162
194
|
|
|
163
195
|
---
|
package/dist/canvas.d.ts
CHANGED
|
@@ -3,5 +3,5 @@ import type { CompressionResult } from "./types";
|
|
|
3
3
|
* Main-thread image compressor fallback.
|
|
4
4
|
* Uses OffscreenCanvas if available, otherwise falls back to HTMLCanvasElement.
|
|
5
5
|
*/
|
|
6
|
-
export declare function compressWithMainThread(blob: Blob, maxWidth: number | undefined, maxHeight: number | undefined, quality: number, mimeType: string,
|
|
6
|
+
export declare function compressWithMainThread(blob: Blob, maxWidth: number | undefined, maxHeight: number | undefined, quality: number, mimeType: string, signal?: AbortSignal): Promise<CompressionResult>;
|
|
7
7
|
//# sourceMappingURL=canvas.d.ts.map
|
package/dist/canvas.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"canvas.d.ts","sourceRoot":"","sources":["../src/canvas.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAC;AAEjD;;;GAGG;AACH,wBAAsB,sBAAsB,CAC1C,IAAI,EAAE,IAAI,EACV,QAAQ,EAAE,MAAM,GAAG,SAAS,EAC5B,SAAS,EAAE,MAAM,GAAG,SAAS,EAC7B,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,MAAM,EAChB,
|
|
1
|
+
{"version":3,"file":"canvas.d.ts","sourceRoot":"","sources":["../src/canvas.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAC;AAEjD;;;GAGG;AACH,wBAAsB,sBAAsB,CAC1C,IAAI,EAAE,IAAI,EACV,QAAQ,EAAE,MAAM,GAAG,SAAS,EAC5B,SAAS,EAAE,MAAM,GAAG,SAAS,EAC7B,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,MAAM,EAChB,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,iBAAiB,CAAC,CAwF5B"}
|
package/dist/index.cjs
CHANGED
|
@@ -1,44 +1,36 @@
|
|
|
1
|
-
var{defineProperty:v,getOwnPropertyNames:k,getOwnPropertyDescriptor:W}=Object,A=Object.prototype.hasOwnProperty;function B(e){return this[e]}var S=(e)=>{var t=(L??=new WeakMap).get(e),n;if(t)return t;if(t=v({},"__esModule",{value:!0}),e&&typeof e==="object"||typeof e==="function"){for(var r of k(e))if(!A.call(t,r))v(t,r,{get:B.bind(e,r),enumerable:!(n=W(e,r))||n.enumerable})}return L.set(e,t),t},L;var P=(e)=>e;function j(e,t){this[e]=P.bind(null,t)}var D=(e,t)=>{for(var n in t)v(e,n,{get:t[n],enumerable:!0,configurable:!0,set:j.bind(t,n)})};var T={};D(T,{compressImage:()=>I,compressWithMainThread:()=>g,compressWithWorker:()=>C,default:()=>F,extractMetadataSegments:()=>y,normalizeExifOrientation:()=>R,spliceMetadataIntoBlob:()=>M});module.exports=S(T);async function g(e,t,n,r,f,c,o){if(o?.aborted)throw new DOMException("Compression aborted","AbortError");if(typeof OffscreenCanvas<"u"&&typeof createImageBitmap<"u"){let s;try{s=await createImageBitmap(e,{imageOrientation:"from-image"})}catch{s=await createImageBitmap(e)}let i=s.width,a=s.height;if(t&&i>t)a=Math.round(a*t/i),i=t;if(n&&a>n)i=Math.round(i*n/a),a=n;let d=new OffscreenCanvas(i,a),u=d.getContext("2d");if(!u)throw Error("OffscreenCanvas 2D context unavailable");if(f==="image/jpeg"&&c)u.fillStyle=c,u.fillRect(0,0,i,a);return u.drawImage(s,0,0,i,a),s.close(),{blob:await d.convertToBlob({type:f,quality:r}),width:i,height:a}}return new Promise((s,i)=>{if(typeof window>"u"||typeof document>"u"){s({blob:e,width:0,height:0});return}let a=new Image,d=URL.createObjectURL(e),u=()=>{URL.revokeObjectURL(d),i(new DOMException("Compression aborted","AbortError"))};if(o){if(o.aborted)return u();o.addEventListener("abort",u,{once:!0})}a.onload=()=>{URL.revokeObjectURL(d);let{naturalWidth:p,naturalHeight:l}=a;if(t&&p>t)l=Math.round(l*t/p),p=t;if(n&&l>n)p=Math.round(p*n/l),l=n;let h=document.createElement("canvas");h.width=p,h.height=l;let m=h.getContext("2d");if(!m){i(Error("Canvas 2D context unavailable"));return}if(f==="image/jpeg"&&c)m.fillStyle=c,m.fillRect(0,0,p,l);m.drawImage(a,0,0,p,l),h.toBlob((w)=>{if(w)s({blob:w,width:p,height:l});else i(Error("Canvas compression failed to produce blob"))},f,r)},a.onerror=()=>{URL.revokeObjectURL(d),i(Error("Failed to load image for compression"))},a.src=d})}async function y(e){let t=Math.min(e.size,262144),n=await e.slice(0,t).arrayBuffer(),r=new DataView(n);if(r.byteLength<4||r.getUint16(0)!==65496)return[];let f=[],c=2;while(c+4<r.byteLength){let o=r.getUint16(c);if(o===65498||o===65497||(o&65280)!==65280)break;let s=r.getUint16(c+2);if(s<2||c+2+s>r.byteLength)break;if(o===65505||o===65506){let i=new Uint8Array(n.slice(c,c+2+s));R(i),f.push(i)}c+=2+s}return f}function R(e){if(e.length<14)return!1;if(!(e[0]===255&&e[1]===225&&e[4]===69&&e[5]===120&&e[6]===105&&e[7]===102&&e[8]===0&&e[9]===0))return!1;let n=10,r=new DataView(e.buffer,e.byteOffset,e.byteLength),f=r.getUint16(n)===18761;if(!f&&r.getUint16(n)!==19789)return!1;if(r.getUint16(n+2,f)!==42)return!1;let c=r.getUint32(n+4,f),o=n+c;if(o+2>e.length)return!1;let s=r.getUint16(o,f);for(let i=0;i<s;i++){let a=o+2+i*12;if(a+12>e.length)break;if(r.getUint16(a,f)===274)return r.setUint16(a+8,1,f),!0}return!1}async function M(e,t){if(t.length===0)return e;let n=await e.slice(0,32).arrayBuffer(),r=new DataView(n);if(r.byteLength<4||r.getUint16(0)!==65496)return e;let f=2;if(r.getUint16(2)===65504)f=4+r.getUint16(4);let c=e.slice(0,f),o=e.slice(f),s=t.map((i)=>i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength));return new Blob([c,...s,o],{type:e.type||"image/jpeg"})}var z=`
|
|
1
|
+
var{defineProperty:R,getOwnPropertyNames:ie,getOwnPropertyDescriptor:oe}=Object,se=Object.prototype.hasOwnProperty;function fe(e){return this[e]}var ce=(e)=>{var t=(V??=new WeakMap).get(e),r;if(t)return t;if(t=R({},"__esModule",{value:!0}),e&&typeof e==="object"||typeof e==="function"){for(var n of ie(e))if(!se.call(t,n))R(t,n,{get:fe.bind(e,n),enumerable:!(r=oe(e,n))||r.enumerable})}return V.set(e,t),t},V;var ue=(e)=>e;function pe(e,t){this[e]=ue.bind(null,t)}var de=(e,t)=>{for(var r in t)R(e,r,{get:t[r],enumerable:!0,configurable:!0,set:pe.bind(t,r)})};var Me={};de(Me,{compressImage:()=>ee,compressWithMainThread:()=>C,compressWithWorker:()=>z,default:()=>Fe,detectInputMime:()=>M,extractMetadataSegments:()=>L,getImageMetadata:()=>B,getJpegMetadata:()=>H,insertWebPExif:()=>T,normalizeExifOrientation:()=>P,spliceMetadataIntoBlob:()=>W,spliceWebpMetadata:()=>k});module.exports=ce(Me);function M(e,t){let r=e.type;if(r==="image/jpeg"||r==="image/webp"||r==="image/png")return r;let n=t??(e instanceof File?e.name:"");if(/\.(jpe?g)$/i.test(n))return"image/jpeg";if(/\.webp$/i.test(n))return"image/webp";if(/\.png$/i.test(n))return"image/png";return}async function j(e){if(e.size<4)return null;let t=await e.slice(0,12).arrayBuffer(),r=new DataView(t);if(r.byteLength>=2&&r.getUint16(0)===65496)return"jpeg";if(r.byteLength>=12&&r.getUint32(0,!1)===1380533830&&r.getUint32(8,!1)===1464156752)return"webp";return null}function v(e,t,r,n){if(r&&e>r)t=Math.round(t*r/e),e=r;if(n&&t>n)e=Math.round(e*n/t),t=n;return{width:e,height:t}}function w(e){e?.throwIfAborted()}async function C(e,t,r,n,a,i){if(w(i),typeof OffscreenCanvas<"u"&&typeof createImageBitmap<"u"){let c=await createImageBitmap(e),{width:u,height:o}=v(c.width,c.height,t,r),s=new OffscreenCanvas(u,o),f=s.getContext("2d");if(!f)throw Error("OffscreenCanvas 2D context unavailable");return f.drawImage(c,0,0,u,o),c.close(),{blob:await s.convertToBlob({type:a,quality:n}),width:u,height:o}}return new Promise((c,u)=>{if(typeof window>"u"||typeof document>"u"){c({blob:e,width:0,height:0});return}let o=new Image,s=URL.createObjectURL(e),f=!1,p=()=>{if(f)return;f=!0,URL.revokeObjectURL(s),u(new DOMException("Compression aborted","AbortError"))},d=(l)=>{if(f)return;f=!0,i?.removeEventListener("abort",p),l()};if(i){if(i.aborted){p();return}i.addEventListener("abort",p,{once:!0})}o.onload=()=>{if(f)return;URL.revokeObjectURL(s);let{width:l,height:m}=v(o.naturalWidth,o.naturalHeight,t,r),g=document.createElement("canvas");g.width=l,g.height=m;let b=g.getContext("2d");if(!b){d(()=>u(Error("Canvas 2D context unavailable")));return}b.drawImage(o,0,0,l,m),g.toBlob((U)=>{if(U)d(()=>c({blob:U,width:l,height:m}));else d(()=>u(Error("Canvas compression failed to produce blob")))},a,n)},o.onerror=()=>{URL.revokeObjectURL(s),d(()=>u(Error("Failed to load image for compression")))},o.src=s})}var A=[69,120,105,102,0,0];function _(e,t=0){if(e.length<t+A.length)return!1;for(let r=0;r<A.length;r++)if(e[t+r]!==A[r])return!1;return!0}function O(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function ge(e,t,r){return new Uint8Array(e.buffer.slice(e.byteOffset+t,e.byteOffset+r))}async function*le(e,t){let r=0,n=t,a=2;while(!0){if(a+4>n.byteLength){let s=r+a;if(s+4>e.size)return;let f=await e.slice(s,s+262144).arrayBuffer();if(f.byteLength<4)return;r=s,n=new DataView(f),a=0;continue}let i=n.getUint16(a);if(i===65498||i===65497||(i&65280)!==65280)return;let c=n.getUint16(a+2);if(c<2)return;let u=a+2+c,o=r+u;if(o>e.size)return;if(i===65505||i===65506){let s=u<=n.byteLength?ge(n,a,u):new Uint8Array(await e.slice(r+a,o).arrayBuffer());yield{kind:i===65505?"jpeg-app1":"jpeg-app2",bytes:s}}a=u}}async function*me(e,t){let r=e.size,n=12;while(n+8<=r){let a,i;if(n+8<=t.byteLength)a=t.getUint32(n,!1),i=t.getUint32(n+4,!0);else{let s=await e.slice(n,n+8).arrayBuffer();if(s.byteLength<8)return;let f=new DataView(s);a=f.getUint32(0,!1),i=f.getUint32(4,!0)}let c=i+1&-2,u=a===1163413830,o=a===1229144912;if(u&&i>=6||o){let s=n+8+i;if(s>r)return;if(i>0){let f=new Uint8Array(await e.slice(n+8,s).arrayBuffer());yield{kind:u?"webp-exif":"webp-iccp",bytes:f}}}n+=8+c}}async function*G(e){let t=Math.min(e.size,262144),r=await e.slice(0,t).arrayBuffer(),n=new DataView(r);if(n.byteLength<4)return;if(n.getUint16(0)===65496){yield*le(e,n);return}if(n.byteLength>=12&&n.getUint32(0,!1)===1380533830&&n.getUint32(8,!1)===1464156752)yield*me(e,n)}function he(e){let t=_(e)?e.subarray(A.length):e,r=2+A.length+t.length,n=new Uint8Array(2+r);return n[0]=255,n[1]=225,n[2]=r>>8&255,n[3]=r&255,n.set(A,4),n.set(t,4+A.length),n}function xe(e){let t=[73,67,67,95,80,82,79,70,73,76,69,0,1,1],r=2+t.length+e.length,n=new Uint8Array(2+r);return n[0]=255,n[1]=226,n[2]=r>>8&255,n[3]=r&255,n.set(t,4),n.set(e,4+t.length),n}async function L(e){let t=[];for await(let r of G(e))switch(r.kind){case"jpeg-app1":{P(r.bytes),t.push(r.bytes);break}case"jpeg-app2":{t.push(r.bytes);break}case"webp-exif":{let n=he(r.bytes);P(n),t.push(n);break}case"webp-iccp":{t.push(xe(r.bytes));break}}return t}function P(e){if(e.length<14)return!1;if(!(e[0]===255&&e[1]===225&&e[4]===69&&e[5]===120&&e[6]===105&&e[7]===102&&e[8]===0&&e[9]===0))return!1;let r=10,n=new DataView(e.buffer,e.byteOffset,e.byteLength),a=n.getUint16(r)===18761;if(!a&&n.getUint16(r)!==19789)return!1;if(n.getUint16(r+2,a)!==42)return!1;let i=n.getUint32(r+4,a),c=r+i;if(c+2>e.length)return!1;let u=n.getUint16(c,a);for(let o=0;o<u;o++){let s=c+2+o*12;if(s+12>e.length)break;if(n.getUint16(s,a)===274)return n.setUint16(s+8,1,a),!0}return!1}async function W(e,t){if(t.length===0)return e;let r=await e.slice(0,32).arrayBuffer(),n=new DataView(r);if(n.byteLength<4||n.getUint16(0)!==65496)return e;let a=2;if(n.getUint16(2)===65504)a=4+n.getUint16(4);let i=e.slice(0,a),c=e.slice(a),u=t.map((o)=>o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength));return new Blob([i,...u,c],{type:e.type||"image/jpeg"})}async function B(e){let t={hasExif:!1,hasIccProfile:!1,colorSpace:"sRGB (Standard)"};for await(let r of G(e))if(r.kind==="jpeg-app1"){if(_(r.bytes,4))t.hasExif=!0,X(O(r.bytes),10,t)}else if(r.kind==="webp-exif")t.hasExif=!0,X(O(r.bytes),_(r.bytes)?A.length:0,t);else t.hasIccProfile=!0,t.colorSpace="ICC profile embedded";return t}var H=B;function X(e,t,r){if(t+8>e.byteLength)return;let n=e.getUint16(t)===18761;if(!n&&e.getUint16(t)!==19789)return;if(e.getUint16(t+2,n)!==42)return;let a=e.getUint32(t+4,n),i=t+a;if(i+2>e.byteLength)return;let c,u=e.getUint16(i,n);for(let o=0;o<u;o++){let s=i+2+o*12;if(s+12>e.byteLength)break;let f=e.getUint16(s,n),p=e.getUint16(s+2,n),d=e.getUint32(s+4,n);if(f===274)r.orientation=e.getUint16(s+8,n);else if(f===271&&p===2)r.make=F(e,t,s,d,n);else if(f===272&&p===2)r.model=F(e,t,s,d,n);else if(f===306&&p===2)r.dateTime=F(e,t,s,d,n);else if(f===34665&&(p===3||p===4))c=e.getUint32(s+8,n)}if(c){let o=t+c;if(o+2<=e.byteLength){let s=e.getUint16(o,n);for(let f=0;f<s;f++){let p=o+2+f*12;if(p+12>e.byteLength)break;let d=e.getUint16(p,n),l=e.getUint16(p+2,n),m=e.getUint32(p+4,n);if((d===36867||d===36868)&&l===2&&!r.dateTime)r.dateTime=F(e,t,p,m,n)}}}}function F(e,t,r,n,a){if(n<=4){let s="";for(let f=0;f<n;f++){let p=e.getUint8(r+8+f);if(p===0)break;s+=String.fromCharCode(p)}return s.trim()}let i=e.getUint32(r+8,a),c=t+i;if(c>=e.byteLength)return"";let u=Math.min(n,e.byteLength-c),o="";for(let s=0;s<u;s++){let f=e.getUint8(c+s);if(f===0)break;o+=String.fromCharCode(f)}return o.trim()}var Z=new Set(["VP8 ","VP8L","ALPH","ANIM","ANMF"]);function D(e,t){return String.fromCharCode(e[t],e[t+1],e[t+2],e[t+3])}function J(e,t){return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(t,!0)}function K(e,t,r){new DataView(e.buffer,e.byteOffset,e.byteLength).setUint32(t,r,!0)}function Q(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16}function q(e,t,r){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255}function be(e){if(e.length<12)throw Error("Invalid WebP: file is too small");if(D(e,0)!=="RIFF"||D(e,8)!=="WEBP")throw Error("Invalid WebP: missing RIFF/WEBP header");let t=J(e,4);if(Math.abs(t+8-e.length)>1&&t+8>e.length)throw Error("Invalid WebP: RIFF size mismatch");let r=[],n=12;while(n<e.length){if(n+8>e.length)break;let a=D(e,n),i=J(e,n+4),c=n+8,u=c+i,o=u+(i&1);if(u>e.length)break;r.push({fourCC:a,data:e.subarray(c,u)}),n=Math.min(o,e.length)}return r}function ye(e){let t=e.find((a)=>a.fourCC==="VP8X");if(t&&t.data.length>=10){let a=1+Q(t.data,4),i=1+Q(t.data,7),c=(t.data[0]&16)!==0;return{width:a,height:i,alpha:c}}let r=e.find((a)=>a.fourCC==="VP8 "),n=e.find((a)=>a.fourCC==="VP8L");if(r){let a=r.data;if(a.length>=10&&a[3]===157&&a[4]===1&&a[5]===42){let i=(a[6]|a[7]<<8)&16383,c=(a[8]|a[9]<<8)&16383;if(i&&c)return{width:i,height:c,alpha:!1}}}if(n){let a=n.data;if(a.length>=5&&a[0]===47){let i=a[1]|a[2]<<8|a[3]<<16|a[4]<<24,c=(i&16383)+1,u=(i>>>14&16383)+1,o=(i>>>28&1)!==0;return{width:c,height:u,alpha:o}}}return null}function we(e,t,r,n,a){let i=ye(e),c=i?.width??n??1,u=i?.height??a??1,o=i?.alpha??!1,s=0;if(t)s|=8;if(r||e.some((p)=>p.fourCC==="ICCP"))s|=32;if(o||e.some((p)=>p.fourCC==="ALPH"))s|=16;if(e.some((p)=>p.fourCC==="XMP "))s|=4;if(e.some((p)=>p.fourCC==="ANIM"||p.fourCC==="ANMF"))s|=2;let f=new Uint8Array(10);return f[0]=s,q(f,4,Math.max(0,c-1)),q(f,7,Math.max(0,u-1)),{fourCC:"VP8X",data:f}}function Ce(e){if(e.length===0)throw Error("EXIF data cannot be empty");let t=e;if(t.length>=4&&t[0]===255&&t[1]===225)t=t.subarray(4);let n=t.length>=6&&t[0]===69&&t[1]===120&&t[2]===105&&t[3]===102&&t[4]===0&&t[5]===0?t.subarray(6):t;if(n.length<8)throw Error("Invalid EXIF TIFF header");let a=n[0]===73&&n[1]===73,i=n[0]===77&&n[1]===77;if(!a&&!i)throw Error("Invalid EXIF byte order");if((a?n[2]|n[3]<<8:n[2]<<8|n[3])!==42)throw Error("Invalid EXIF TIFF magic");return n}function Ae(e){let t=e;if(t.length>=4&&t[0]===255&&t[1]===226)t=t.subarray(4);if(t.length>=14&&t[0]===73&&t[1]===67&&t[2]===67&&t[3]===95&&t[4]===80&&t[5]===82&&t[6]===79&&t[7]===70&&t[8]===73&&t[9]===76&&t[10]===69&&t[11]===0)return t.subarray(14);return t}function Ie(e){let t=12;for(let a of e)t+=8+a.data.length+(a.data.length&1);if(t-8>4294967295)throw Error("WebP file exceeds RIFF size limit");let r=new Uint8Array(t);r.set([82,73,70,70],0),K(r,4,t-8),r.set([87,69,66,80],8);let n=12;for(let a of e){for(let i=0;i<4;i++)r[n+i]=a.fourCC.charCodeAt(i);if(K(r,n+4,a.data.length),r.set(a.data,n+8),n+=8+a.data.length,a.data.length&1)r[n]=0,n++}return r}function T(e,t,r,n,a){if(!(e instanceof Uint8Array))throw TypeError("webp must be a Uint8Array");let i=t?Ce(t):void 0,c=r?Ae(r):void 0,u=be(e),o=u.find((g)=>g.fourCC==="EXIF"),s=u.find((g)=>g.fourCC==="ICCP"),f=i?{fourCC:"EXIF",data:i}:o,p=c?{fourCC:"ICCP",data:c}:s,d=u.filter((g)=>g.fourCC!=="VP8X"&&g.fourCC!=="EXIF"&&g.fourCC!=="ICCP"),l=[];if(p)l.push(p);if(l.push(...d.filter((g)=>Z.has(g.fourCC))),f)l.push(f);l.push(...d.filter((g)=>!Z.has(g.fourCC)));let m=we(l,Boolean(f),Boolean(p),n,a);return Ie([m,...l])}async function k(e,t,r,n){let a,i;for(let o of t)if(o.length>=14&&o[0]===255&&o[1]===225)a=o;else if(o.length>=18&&o[0]===255&&o[1]===226)i=o;if(!a&&!i)return e;let c=new Uint8Array(await e.arrayBuffer()),u=T(c,a,i,r,n);return new Blob([u.buffer.slice(0,u.byteLength)],{type:"image/webp"})}var Ue=`
|
|
2
|
+
function computeTargetSize(width, height, maxWidth, maxHeight) {
|
|
3
|
+
if (maxWidth && width > maxWidth) {
|
|
4
|
+
height = Math.round((height * maxWidth) / width);
|
|
5
|
+
width = maxWidth;
|
|
6
|
+
}
|
|
7
|
+
if (maxHeight && height > maxHeight) {
|
|
8
|
+
width = Math.round((width * maxHeight) / height);
|
|
9
|
+
height = maxHeight;
|
|
10
|
+
}
|
|
11
|
+
return { width, height };
|
|
12
|
+
}
|
|
2
13
|
self.onmessage = async (e) => {
|
|
3
|
-
const {
|
|
14
|
+
const { blob, maxWidth, maxHeight, quality, mimeType } = e.data;
|
|
4
15
|
try {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
bitmap
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
let width = bitmap.width;
|
|
13
|
-
let height = bitmap.height;
|
|
14
|
-
|
|
15
|
-
if (maxWidth && width > maxWidth) {
|
|
16
|
-
height = Math.round((height * maxWidth) / width);
|
|
17
|
-
width = maxWidth;
|
|
18
|
-
}
|
|
19
|
-
if (maxHeight && height > maxHeight) {
|
|
20
|
-
width = Math.round((width * maxHeight) / height);
|
|
21
|
-
height = maxHeight;
|
|
22
|
-
}
|
|
23
|
-
|
|
16
|
+
const bitmap = await createImageBitmap(blob);
|
|
17
|
+
const { width, height } = computeTargetSize(
|
|
18
|
+
bitmap.width,
|
|
19
|
+
bitmap.height,
|
|
20
|
+
maxWidth,
|
|
21
|
+
maxHeight,
|
|
22
|
+
);
|
|
24
23
|
const canvas = new OffscreenCanvas(width, height);
|
|
25
24
|
const ctx = canvas.getContext("2d");
|
|
26
25
|
if (!ctx) throw new Error("OffscreenCanvas 2D context unavailable");
|
|
27
|
-
|
|
28
|
-
if (mimeType === "image/jpeg" && backgroundColor) {
|
|
29
|
-
ctx.fillStyle = backgroundColor;
|
|
30
|
-
ctx.fillRect(0, 0, width, height);
|
|
31
|
-
}
|
|
32
|
-
|
|
33
26
|
ctx.drawImage(bitmap, 0, 0, width, height);
|
|
34
27
|
bitmap.close();
|
|
35
|
-
|
|
36
28
|
const outputBlob = await canvas.convertToBlob({ type: mimeType, quality });
|
|
37
|
-
self.postMessage({
|
|
29
|
+
self.postMessage({ success: true, blob: outputBlob, width, height });
|
|
38
30
|
} catch (err) {
|
|
39
|
-
self.postMessage({
|
|
31
|
+
self.postMessage({ success: false, error: err?.message || String(err) });
|
|
40
32
|
}
|
|
41
33
|
};
|
|
42
|
-
`;async function
|
|
34
|
+
`;async function z(e,t,r,n,a,i){if(w(i),typeof Worker>"u"||typeof OffscreenCanvas>"u")return C(e,t,r,n,a,i);let c=null;try{let o=new Blob([Ue],{type:"application/javascript"});c=URL.createObjectURL(o)}catch{return C(e,t,r,n,a,i)}let u;try{u=new Worker(c)}catch{return URL.revokeObjectURL(c),c=null,C(e,t,r,n,a,i)}return new Promise((o,s)=>{function f(){if(u.terminate(),i?.removeEventListener("abort",p),c)URL.revokeObjectURL(c),c=null}let p=()=>{f(),s(new DOMException("Compression aborted","AbortError"))};if(i){if(i.aborted){p();return}i.addEventListener("abort",p,{once:!0})}u.onmessage=(d)=>{if(f(),d.data.success)o({blob:d.data.blob,width:d.data.width,height:d.data.height});else s(Error(d.data.error||"Worker compression failed"))},u.onerror=(d)=>{f(),s(Error(d.message||"Worker execution failed"))},u.postMessage({blob:e,maxWidth:t,maxHeight:r,quality:n,mimeType:a})})}var Y={extract:{progress:10,stage:"Extracting metadata"},compress:{progress:30,stage:"Compressing pixels"},optimize:{progress:65,stage:"Optimizing file size"},preserve:{progress:85,stage:"Preserving metadata"},complete:{progress:100,stage:"Complete"}};function Ee(e,t,r){if(t==="image/webp")return console.warn("[imagepressor] Warning: WebP quality is set to 1.0 (100%) without a maxSizeMB ceiling. Browsers may encode WebP at quality 1.0 losslessly (VP8L), which can significantly inflate photographic image file sizes (+45% or more). Returning original image to prevent file size increase."),r?.(100,"Completed (original image preserved to prevent WebP 100% inflation)"),e;if(t==="image/jpeg")return console.warn("[imagepressor] Warning: JPEG quality is set to 1.0 (100%) without a maxSizeMB ceiling or resizing. Returning original image to preserve full fidelity and prevent re-compression generation loss."),r?.(100,"Completed (original image preserved to prevent JPEG re-compression)"),e;return null}async function ee(e,t={}){if(!(typeof OffscreenCanvas<"u"&&typeof createImageBitmap<"u")&&!(typeof document<"u"&&typeof Image<"u"))return e;let a=M(e),i=a==="image/webp"||a==="image/png"?"image/webp":"image/jpeg",{maxSizeMB:c=Number.POSITIVE_INFINITY,maxWidth:u,maxHeight:o,quality:s=0.85,mimeType:f=i,preserveMetadata:p=!0,useWebWorker:d=!0,strict:l,signal:m,onProgress:g}=t,b=(h)=>g?.(Y[h].progress,Y[h].stage);w(m);let U=!a||a===f,I=c*1024*1024;if(s>=1&&(!c||!Number.isFinite(I))&&!u&&!o){let h=Ee(e,f,g);if(h)return h}if(Number.isFinite(I)&&e.size<=I&&!u&&!o&&(!a||a===f)&&s>=1)return e;b("extract");let E=[],te=await j(e);if(p&&te){try{E=await L(e)}catch{}if(E.length===0)console.warn("[imagepressor] Warning: Image does not contain EXIF metadata or an ICC color profile to preserve.")}w(m),b("compress");let N=d?z:C,y=await N(e,u,o,s,f,m);if(Number.isFinite(I)&&y.blob.size>I){b("optimize");let h=Math.sqrt(I/y.blob.size)*0.95,S=Math.max(800,Math.round(y.width*Math.min(0.85,h))),ae=Math.max(0.65,s*0.85);y=await N(y.blob,S,void 0,ae,f,m)}w(m),b("preserve");let x=y.blob;if(E.length>0)try{if(f==="image/jpeg")x=await W(x,E);else if(f==="image/webp")x=await k(x,E,y.width,y.height)}catch(h){console.warn("[imagepressor] Warning: Could not preserve metadata on the compressed image; returning pixels without metadata.",h)}let ne=l!==void 0?l:U,re=Number.isFinite(I);if(x.size>=e.size&&ne&&!u&&!o&&!re)return console.warn(`[imagepressor] Notice: Compression to ${f} resulted in a larger file (${(x.size/1048576).toFixed(2)} MB vs original ${(e.size/1048576).toFixed(2)} MB). Returning original file to prevent file size expansion.`),e;if(x.size>=e.size&&!u&&!o&&!U)console.warn(`[imagepressor] Notice: Format conversion from ${a||"original"} to ${f} increased file size from ${(e.size/1048576).toFixed(2)} MB to ${(x.size/1048576).toFixed(2)} MB. Modern formats like WebP are ~30% more efficient than legacy JPEG. To prevent expansion, set strict: true or specify maxSizeMB.`);if(b("complete"),e instanceof File){let h=f==="image/webp"?"webp":"jpg",S=e.name.replace(/\.[^/.]+$/,"")||"photo";return new File([x],`${S}.${h}`,{type:f,lastModified:e.lastModified})}return x}var Fe=ee;
|
|
43
35
|
|
|
44
|
-
//# debugId=
|
|
36
|
+
//# debugId=977F7AECF7E5160B64756E2164756E21
|