imagepressor 0.0.0-stage → 0.1.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/README.md +173 -2
- package/dist/canvas.d.ts +7 -0
- package/dist/canvas.d.ts.map +1 -0
- package/dist/index.cjs +44 -0
- package/dist/index.cjs.map +13 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +44 -0
- package/dist/index.js.map +13 -0
- package/dist/jpeg.d.ts +16 -0
- package/dist/jpeg.d.ts.map +1 -0
- package/dist/types.d.ts +28 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/worker.d.ts +7 -0
- package/dist/worker.d.ts.map +1 -0
- package/package.json +53 -4
package/README.md
CHANGED
|
@@ -1,3 +1,174 @@
|
|
|
1
|
-
#
|
|
1
|
+
# imagepressor
|
|
2
2
|
|
|
3
|
-
|
|
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.
|
|
4
|
+
|
|
5
|
+
[](https://www.npmjs.com/package/imagepressor)
|
|
6
|
+
[](https://github.com/ijaik/imagepressor/blob/main/LICENSE)
|
|
7
|
+
|
|
8
|
+
---
|
|
9
|
+
|
|
10
|
+
## Highlights
|
|
11
|
+
|
|
12
|
+
- **Off-Main-Thread Processing:** Resizes and compresses images inside a dedicated Web Worker via `createImageBitmap` and `OffscreenCanvas`. No UI freezing, even with 30MB+ camera uploads.
|
|
13
|
+
- **100% CSP-Safe & Offline Ready:** Self-contained inline Web Worker. Never loads scripts from public CDNs like jsDelivr, ensuring full compliance with strict Content Security Policies.
|
|
14
|
+
- **Preserves True Colors (Display P3):** Automatically detects and re-injects APP2 (ICC color profile) binary segments into compressed JPEGs, preventing washed-out colors on iPhones and modern monitors.
|
|
15
|
+
- **Non-Destructive EXIF:** Preserves camera model, focal length, ISO, shutter speed, and capture timestamp.
|
|
16
|
+
- **Automatic Orientation Normalization:** Resets the EXIF orientation tag in-place to `1`, permanently preventing sideways/double-rotated images in external viewers.
|
|
17
|
+
- **Transparency Protection:** Pre-fills transparent pixels before converting PNG/WebP to JPEG, eliminating ugly black backgrounds.
|
|
18
|
+
- **Zero Runtime Dependencies:** Pure TypeScript and native Web Platform APIs. Under 7 KB minified.
|
|
19
|
+
|
|
20
|
+
---
|
|
21
|
+
|
|
22
|
+
## Installation
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
bun add imagepressor
|
|
26
|
+
# or
|
|
27
|
+
npm install imagepressor
|
|
28
|
+
# or
|
|
29
|
+
pnpm add imagepressor
|
|
30
|
+
# or
|
|
31
|
+
yarn add imagepressor
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
---
|
|
35
|
+
|
|
36
|
+
## Quick Start
|
|
37
|
+
|
|
38
|
+
Compress an image file down to under 1 MB and max 1920px width:
|
|
39
|
+
|
|
40
|
+
```typescript
|
|
41
|
+
import { compressImage } from "imagepressor";
|
|
42
|
+
|
|
43
|
+
const fileInput = document.querySelector('input[type="file"]');
|
|
44
|
+
|
|
45
|
+
fileInput.addEventListener("change", async (event) => {
|
|
46
|
+
const file = event.target.files[0];
|
|
47
|
+
if (!file) return;
|
|
48
|
+
|
|
49
|
+
try {
|
|
50
|
+
const compressed = await compressImage(file, {
|
|
51
|
+
maxSizeMB: 1, // Target maximum size: 1 MB
|
|
52
|
+
maxWidth: 1920, // Max width in pixels (maintains aspect ratio)
|
|
53
|
+
quality: 0.85, // Visual quality (0.0 to 1.0)
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
console.log("Original size:", file.size);
|
|
57
|
+
console.log("Compressed size:", compressed.size);
|
|
58
|
+
|
|
59
|
+
// Upload 'compressed' (File or Blob) to your server, S3, Cloudinary, etc.
|
|
60
|
+
} catch (error) {
|
|
61
|
+
console.error("Compression failed:", error);
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
---
|
|
67
|
+
|
|
68
|
+
## Advanced Usage
|
|
69
|
+
|
|
70
|
+
### 1. Real-Time Progress Tracking
|
|
71
|
+
|
|
72
|
+
Keep your users informed during large multi-pass compressions:
|
|
73
|
+
|
|
74
|
+
```typescript
|
|
75
|
+
const compressed = await compressImage(largeFile, {
|
|
76
|
+
maxSizeMB: 1.5,
|
|
77
|
+
maxWidth: 2560,
|
|
78
|
+
onProgress: (percent, stage) => {
|
|
79
|
+
console.log(`[${percent}%] Current stage: ${stage}`);
|
|
80
|
+
// Stages: "Extracting metadata", "Compressing pixels", "Optimizing file size", "Preserving metadata", "Complete"
|
|
81
|
+
},
|
|
82
|
+
});
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
### 2. Cancellation with AbortSignal
|
|
86
|
+
|
|
87
|
+
Cancel compression instantly if the user navigates away or clicks "Cancel":
|
|
88
|
+
|
|
89
|
+
```typescript
|
|
90
|
+
const controller = new AbortController();
|
|
91
|
+
|
|
92
|
+
// Cancel button click handler
|
|
93
|
+
cancelButton.addEventListener("click", () => {
|
|
94
|
+
controller.abort();
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
try {
|
|
98
|
+
const result = await compressImage(file, {
|
|
99
|
+
maxSizeMB: 1,
|
|
100
|
+
signal: controller.signal,
|
|
101
|
+
});
|
|
102
|
+
} catch (err) {
|
|
103
|
+
if (err.name === "AbortError") {
|
|
104
|
+
console.log("Compression cancelled by user.");
|
|
105
|
+
} else {
|
|
106
|
+
console.error("An unexpected error occurred:", err);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
### 3. Converting Formats (PNG/WebP to JPEG)
|
|
112
|
+
|
|
113
|
+
When converting images with transparency to JPEG, specify a custom background color (defaults to `#ffffff`):
|
|
114
|
+
|
|
115
|
+
```typescript
|
|
116
|
+
const jpegFile = await compressImage(pngWithAlpha, {
|
|
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
|
|
124
|
+
|
|
125
|
+
`compressImage` accepts both `File` and `Blob` instances. If given a `File`, it returns a new `File` with the original filename and timestamp. If given a `Blob`, it returns a compressed `Blob`:
|
|
126
|
+
|
|
127
|
+
```typescript
|
|
128
|
+
// From a canvas or camera stream blob
|
|
129
|
+
const compressedBlob = await compressImage(canvasBlob, {
|
|
130
|
+
maxSizeMB: 0.5,
|
|
131
|
+
mimeType: "image/webp",
|
|
132
|
+
});
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
---
|
|
136
|
+
|
|
137
|
+
## Options API Reference
|
|
138
|
+
|
|
139
|
+
| Option | Type | Default | Description |
|
|
140
|
+
| :--- | :--- | :--- | :--- |
|
|
141
|
+
| `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 size ceiling. |
|
|
142
|
+
| `maxWidth` | `number` | `undefined` | Maximum width in pixels. Proportional scaling preserves aspect ratio. |
|
|
143
|
+
| `maxHeight` | `number` | `undefined` | Maximum height in pixels. Proportional scaling preserves aspect ratio. |
|
|
144
|
+
| `quality` | `number` | `0.85` | Compression quality between `0.0` (lowest, smallest) and `1.0` (highest, largest). |
|
|
145
|
+
| `mimeType` | `string` | input type | Target format (`"image/jpeg"`, `"image/webp"`, `"image/png"`). |
|
|
146
|
+
| `preserveMetadata`| `boolean` | `true` | When `true`, extracts and re-injects JPEG EXIF and ICC (Display P3) color profiles. |
|
|
147
|
+
| `backgroundColor` | `string` | `"#ffffff"` | Fill color for transparent pixels when converting alpha images to JPEG. |
|
|
148
|
+
| `useWebWorker` | `boolean` | `true` | Runs off the main thread in a Web Worker. Automatically falls back to main-thread processing if workers or `OffscreenCanvas` are unavailable. |
|
|
149
|
+
| `signal` | `AbortSignal` | `undefined` | An `AbortSignal` to cancel compression immediately and clean up worker memory. |
|
|
150
|
+
| `onProgress` | `function` | `undefined` | Callback receiving `(percent: number, stage: string)`. |
|
|
151
|
+
|
|
152
|
+
---
|
|
153
|
+
|
|
154
|
+
## Browser Support
|
|
155
|
+
|
|
156
|
+
`imgcompressor` is tested and supported across all modern browsers:
|
|
157
|
+
|
|
158
|
+
- **Chrome / Edge / Chromium:** 69+
|
|
159
|
+
- **Firefox:** 105+
|
|
160
|
+
- **Safari / iOS Safari:** 16.4+ (falls back gracefully to main thread on older iOS Safari)
|
|
161
|
+
- **Node.js / SSR:** Safely passes through input files without crashing during server-side rendering.
|
|
162
|
+
|
|
163
|
+
---
|
|
164
|
+
|
|
165
|
+
## Author
|
|
166
|
+
|
|
167
|
+
**Jai**
|
|
168
|
+
GitHub: [@ijaik](https://github.com/ijaik)
|
|
169
|
+
|
|
170
|
+
---
|
|
171
|
+
|
|
172
|
+
## License
|
|
173
|
+
|
|
174
|
+
[MIT](LICENSE)
|
package/dist/canvas.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { CompressionResult } from "./types";
|
|
2
|
+
/**
|
|
3
|
+
* Main-thread image compressor fallback.
|
|
4
|
+
* Uses OffscreenCanvas if available, otherwise falls back to HTMLCanvasElement.
|
|
5
|
+
*/
|
|
6
|
+
export declare function compressWithMainThread(blob: Blob, maxWidth: number | undefined, maxHeight: number | undefined, quality: number, mimeType: string, backgroundColor: string, signal?: AbortSignal): Promise<CompressionResult>;
|
|
7
|
+
//# sourceMappingURL=canvas.d.ts.map
|
|
@@ -0,0 +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,eAAe,EAAE,MAAM,EACvB,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,iBAAiB,CAAC,CAkH5B"}
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
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=`
|
|
2
|
+
self.onmessage = async (e) => {
|
|
3
|
+
const { id, blob, maxWidth, maxHeight, quality, mimeType, backgroundColor } = e.data;
|
|
4
|
+
try {
|
|
5
|
+
let bitmap;
|
|
6
|
+
try {
|
|
7
|
+
bitmap = await createImageBitmap(blob, { imageOrientation: "from-image" });
|
|
8
|
+
} catch {
|
|
9
|
+
bitmap = await createImageBitmap(blob);
|
|
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
|
+
|
|
24
|
+
const canvas = new OffscreenCanvas(width, height);
|
|
25
|
+
const ctx = canvas.getContext("2d");
|
|
26
|
+
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
|
+
ctx.drawImage(bitmap, 0, 0, width, height);
|
|
34
|
+
bitmap.close();
|
|
35
|
+
|
|
36
|
+
const outputBlob = await canvas.convertToBlob({ type: mimeType, quality });
|
|
37
|
+
self.postMessage({ id, success: true, blob: outputBlob, width, height });
|
|
38
|
+
} catch (err) {
|
|
39
|
+
self.postMessage({ id, success: false, error: err?.message || String(err) });
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
`;async function C(e,t,n,r,f,c,o){if(typeof Worker>"u"||typeof OffscreenCanvas>"u")return g(e,t,n,r,f,c,o);let s=null;try{let i=new Blob([z],{type:"application/javascript"});s=URL.createObjectURL(i);let a=new Worker(s),d=a;return await new Promise((u,p)=>{let l=Math.random().toString(36).slice(2),h=()=>{if(d)d.terminate(),d=null;if(s)URL.revokeObjectURL(s),s=null};if(o){if(o.aborted){h(),p(new DOMException("Compression aborted","AbortError"));return}o.addEventListener("abort",()=>{h(),p(new DOMException("Compression aborted","AbortError"))},{once:!0})}a.onmessage=(m)=>{if(m.data.id!==l)return;if(h(),m.data.success)u({blob:m.data.blob,width:m.data.width,height:m.data.height});else p(Error(m.data.error||"Worker compression failed"))},a.onerror=(m)=>{h(),p(Error(m.message||"Worker execution failed"))},a.postMessage({id:l,blob:e,maxWidth:t,maxHeight:n,quality:r,mimeType:f,backgroundColor:c})})}catch{return g(e,t,n,r,f,c,o)}}async function I(e,t={}){if(typeof window>"u"&&typeof self>"u")return e;let{maxSizeMB:n=Number.POSITIVE_INFINITY,maxWidth:r,maxHeight:f,quality:c=0.85,mimeType:o=e.type||"image/jpeg",preserveMetadata:s=!0,backgroundColor:i="#ffffff",useWebWorker:a=!0,signal:d,onProgress:u}=t;if(d?.aborted)throw new DOMException("Compression aborted","AbortError");let p=n*1024*1024;if(e.size<=p&&!r&&!f&&(!e.type||e.type===o))return e;u?.(10,"Extracting metadata");let h=[],m=e.type==="image/jpeg"||e instanceof File&&/\.(jpe?g)$/i.test(e.name);if(s&&m&&o==="image/jpeg")try{h=await y(e)}catch{}if(d?.aborted)throw new DOMException("Compression aborted","AbortError");u?.(30,"Compressing pixels");let w=a?C:g,b=await w(e,r,f,c,o,i,d);if(b.blob.size>p){u?.(65,"Optimizing file size");let E=Math.sqrt(p/b.blob.size)*0.95,U=Math.max(800,Math.round(b.width*Math.min(0.85,E))),O=Math.max(0.65,c*0.85);b=await w(b.blob,U,void 0,O,o,i,d)}if(d?.aborted)throw new DOMException("Compression aborted","AbortError");u?.(85,"Preserving metadata");let x=b.blob;if(h.length>0&&o==="image/jpeg")x=await M(x,h);if(u?.(100,"Complete"),e instanceof File){let E=o==="image/webp"?"webp":o==="image/png"?"png":"jpg",U=e.name.replace(/\.[^/.]+$/,"")||"photo";return new File([x],`${U}.${E}`,{type:o,lastModified:e.lastModified})}return x}var F=I;
|
|
43
|
+
|
|
44
|
+
//# debugId=3BA6709284FC283864756E2164756E21
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/canvas.ts", "../src/jpeg.ts", "../src/worker.ts", "../src/index.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import type { CompressionResult } from \"./types\";\n\n/**\n * Main-thread image compressor fallback.\n * Uses OffscreenCanvas if available, otherwise falls back to HTMLCanvasElement.\n */\nexport async function compressWithMainThread(\n blob: Blob,\n maxWidth: number | undefined,\n maxHeight: number | undefined,\n quality: number,\n mimeType: string,\n backgroundColor: string,\n signal?: AbortSignal,\n): Promise<CompressionResult> {\n if (signal?.aborted) {\n throw new DOMException(\"Compression aborted\", \"AbortError\");\n }\n\n // Fast path: use OffscreenCanvas on main thread if supported\n if (\n typeof OffscreenCanvas !== \"undefined\" &&\n typeof createImageBitmap !== \"undefined\"\n ) {\n let bitmap: ImageBitmap;\n try {\n bitmap = await createImageBitmap(blob, {\n imageOrientation: \"from-image\",\n });\n } catch {\n bitmap = await createImageBitmap(blob);\n }\n\n let width = bitmap.width;\n let height = bitmap.height;\n\n if (maxWidth && width > maxWidth) {\n height = Math.round((height * maxWidth) / width);\n width = maxWidth;\n }\n if (maxHeight && height > maxHeight) {\n width = Math.round((width * maxHeight) / height);\n height = maxHeight;\n }\n\n const canvas = new OffscreenCanvas(width, height);\n const ctx = canvas.getContext(\"2d\");\n if (!ctx) throw new Error(\"OffscreenCanvas 2D context unavailable\");\n\n if (mimeType === \"image/jpeg\" && backgroundColor) {\n ctx.fillStyle = backgroundColor;\n ctx.fillRect(0, 0, width, height);\n }\n\n ctx.drawImage(bitmap, 0, 0, width, height);\n bitmap.close();\n\n const outputBlob = await canvas.convertToBlob({ type: mimeType, quality });\n return { blob: outputBlob, width, height };\n }\n\n // Fallback: standard DOM HTMLCanvasElement\n return new Promise((resolve, reject) => {\n if (typeof window === \"undefined\" || typeof document === \"undefined\") {\n resolve({ blob, width: 0, height: 0 });\n return;\n }\n\n const img = new Image();\n const url = URL.createObjectURL(blob);\n\n const onAbort = () => {\n URL.revokeObjectURL(url);\n reject(new DOMException(\"Compression aborted\", \"AbortError\"));\n };\n\n if (signal) {\n if (signal.aborted) return onAbort();\n signal.addEventListener(\"abort\", onAbort, { once: true });\n }\n\n img.onload = () => {\n URL.revokeObjectURL(url);\n let width = img.naturalWidth;\n let height = img.naturalHeight;\n\n if (maxWidth && width > maxWidth) {\n height = Math.round((height * maxWidth) / width);\n width = maxWidth;\n }\n if (maxHeight && height > maxHeight) {\n width = Math.round((width * maxHeight) / height);\n height = maxHeight;\n }\n\n const canvas = document.createElement(\"canvas\");\n canvas.width = width;\n canvas.height = height;\n const ctx = canvas.getContext(\"2d\");\n if (!ctx) {\n reject(new Error(\"Canvas 2D context unavailable\"));\n return;\n }\n\n if (mimeType === \"image/jpeg\" && backgroundColor) {\n ctx.fillStyle = backgroundColor;\n ctx.fillRect(0, 0, width, height);\n }\n\n ctx.drawImage(img, 0, 0, width, height);\n\n canvas.toBlob(\n (resBlob) => {\n if (resBlob) resolve({ blob: resBlob, width, height });\n else reject(new Error(\"Canvas compression failed to produce blob\"));\n },\n mimeType,\n quality,\n );\n };\n\n img.onerror = () => {\n URL.revokeObjectURL(url);\n reject(new Error(\"Failed to load image for compression\"));\n };\n\n img.src = url;\n });\n}\n",
|
|
6
|
+
"/**\n * Extracts raw EXIF (APP1, 0xFFE1) and ICC Profile (APP2, 0xFFE2) metadata segments from a JPEG file.\n * Reads only the first 256 KB of the file, keeping memory usage minimal.\n */\nexport async function extractMetadataSegments(\n fileOrBlob: Blob,\n): Promise<Uint8Array[]> {\n const chunkSize = Math.min(fileOrBlob.size, 256 * 1024);\n const buffer = await fileOrBlob.slice(0, chunkSize).arrayBuffer();\n const view = new DataView(buffer);\n if (view.byteLength < 4 || view.getUint16(0) !== 0xffd8) return [];\n\n const segments: Uint8Array[] = [];\n let offset = 2;\n\n while (offset + 4 < view.byteLength) {\n const marker = view.getUint16(offset);\n // Stop at Start of Scan (SOS), End of Image (EOI), or invalid marker\n if (\n marker === 0xffda ||\n marker === 0xffd9 ||\n (marker & 0xff00) !== 0xff00\n ) {\n break;\n }\n\n const segLength = view.getUint16(offset + 2);\n if (segLength < 2 || offset + 2 + segLength > view.byteLength) break;\n\n // Preserve APP1 (0xFFE1: Exif / XMP) and APP2 (0xFFE2: ICC color profile)\n if (marker === 0xffe1 || marker === 0xffe2) {\n const segBytes = new Uint8Array(\n buffer.slice(offset, offset + 2 + segLength),\n );\n normalizeExifOrientation(segBytes);\n segments.push(segBytes);\n }\n\n offset += 2 + segLength;\n }\n\n return segments;\n}\n\n/**\n * Normalizes the EXIF Orientation tag to 1 (normal / top-left) in place.\n * Since modern browsers decode and draw upright on canvas (or via createImageBitmap),\n * resetting orientation to 1 prevents external photo viewers from rotating a second time.\n */\nexport function normalizeExifOrientation(segment: Uint8Array): boolean {\n if (segment.length < 14) return false;\n\n // Check for APP1 marker (0xFFE1) + length + 'Exif\\0\\0'\n const isExif =\n segment[0] === 0xff &&\n segment[1] === 0xe1 &&\n segment[4] === 0x45 && // 'E'\n segment[5] === 0x78 && // 'x'\n segment[6] === 0x69 && // 'i'\n segment[7] === 0x66 && // 'f'\n segment[8] === 0x00 &&\n segment[9] === 0x00;\n\n if (!isExif) return false;\n\n const tiffStart = 10;\n const view = new DataView(\n segment.buffer,\n segment.byteOffset,\n segment.byteLength,\n );\n\n const isLittleEndian = view.getUint16(tiffStart) === 0x4949; // 'II'\n if (!isLittleEndian && view.getUint16(tiffStart) !== 0x4d4d) return false; // 'MM'\n if (view.getUint16(tiffStart + 2, isLittleEndian) !== 0x002a) return false; // 42\n\n const firstIfdOffset = view.getUint32(tiffStart + 4, isLittleEndian);\n const ifdStart = tiffStart + firstIfdOffset;\n if (ifdStart + 2 > segment.length) return false;\n\n const tagCount = view.getUint16(ifdStart, isLittleEndian);\n for (let i = 0; i < tagCount; i++) {\n const entryOffset = ifdStart + 2 + i * 12;\n if (entryOffset + 12 > segment.length) break;\n\n const tagId = view.getUint16(entryOffset, isLittleEndian);\n if (tagId === 0x0112) {\n // Orientation tag: write 1 (SHORT = 3, count = 1)\n view.setUint16(entryOffset + 8, 1, isLittleEndian);\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Injects raw original metadata segments into the canvas-compressed JPEG blob.\n */\nexport async function spliceMetadataIntoBlob(\n compressedBlob: Blob,\n metadataSegments: Uint8Array[],\n): Promise<Blob> {\n if (metadataSegments.length === 0) return compressedBlob;\n\n const headBuffer = await compressedBlob.slice(0, 32).arrayBuffer();\n const headView = new DataView(headBuffer);\n if (headView.byteLength < 4 || headView.getUint16(0) !== 0xffd8) {\n return compressedBlob;\n }\n\n let startOffset = 2; // Right after SOI (0xFFD8)\n if (headView.getUint16(2) === 0xffe0) {\n const jfifLen = headView.getUint16(4);\n startOffset = 4 + jfifLen;\n }\n\n const headerPart = compressedBlob.slice(0, startOffset);\n const bodyPart = compressedBlob.slice(startOffset);\n const segmentBuffers: BlobPart[] = metadataSegments.map(\n (s) =>\n s.buffer.slice(s.byteOffset, s.byteOffset + s.byteLength) as ArrayBuffer,\n );\n\n return new Blob([headerPart, ...segmentBuffers, bodyPart], {\n type: compressedBlob.type || \"image/jpeg\",\n });\n}\n",
|
|
7
|
+
"import { compressWithMainThread } from \"./canvas\";\nimport type { CompressionResult } from \"./types\";\n\nconst WORKER_SCRIPT = `\nself.onmessage = async (e) => {\n const { id, blob, maxWidth, maxHeight, quality, mimeType, backgroundColor } = e.data;\n try {\n let bitmap;\n try {\n bitmap = await createImageBitmap(blob, { imageOrientation: \"from-image\" });\n } catch {\n bitmap = await createImageBitmap(blob);\n }\n\n let width = bitmap.width;\n let height = bitmap.height;\n\n if (maxWidth && width > maxWidth) {\n height = Math.round((height * maxWidth) / width);\n width = maxWidth;\n }\n if (maxHeight && height > maxHeight) {\n width = Math.round((width * maxHeight) / height);\n height = maxHeight;\n }\n\n const canvas = new OffscreenCanvas(width, height);\n const ctx = canvas.getContext(\"2d\");\n if (!ctx) throw new Error(\"OffscreenCanvas 2D context unavailable\");\n\n if (mimeType === \"image/jpeg\" && backgroundColor) {\n ctx.fillStyle = backgroundColor;\n ctx.fillRect(0, 0, width, height);\n }\n\n ctx.drawImage(bitmap, 0, 0, width, height);\n bitmap.close();\n\n const outputBlob = await canvas.convertToBlob({ type: mimeType, quality });\n self.postMessage({ id, success: true, blob: outputBlob, width, height });\n } catch (err) {\n self.postMessage({ id, success: false, error: err?.message || String(err) });\n }\n};\n`;\n\n/**\n * Runs image compression off the main thread in a Web Worker using createImageBitmap + OffscreenCanvas.\n * If Web Workers or OffscreenCanvas are blocked or unavailable, automatically falls back to main-thread processing.\n */\nexport async function compressWithWorker(\n blob: Blob,\n maxWidth: number | undefined,\n maxHeight: number | undefined,\n quality: number,\n mimeType: string,\n backgroundColor: string,\n signal?: AbortSignal,\n): Promise<CompressionResult> {\n // Graceful fallback if Web Worker or OffscreenCanvas is unavailable (e.g. older browser or strict environment)\n if (typeof Worker === \"undefined\" || typeof OffscreenCanvas === \"undefined\") {\n return compressWithMainThread(\n blob,\n maxWidth,\n maxHeight,\n quality,\n mimeType,\n backgroundColor,\n signal,\n );\n }\n\n let workerBlobUrl: string | null = null;\n\n try {\n const workerBlob = new Blob([WORKER_SCRIPT], {\n type: \"application/javascript\",\n });\n workerBlobUrl = URL.createObjectURL(workerBlob);\n const activeWorker = new Worker(workerBlobUrl);\n let workerRef: Worker | null = activeWorker;\n\n return await new Promise<CompressionResult>((resolve, reject) => {\n const id = Math.random().toString(36).slice(2);\n\n const cleanup = () => {\n if (workerRef) {\n workerRef.terminate();\n workerRef = null;\n }\n if (workerBlobUrl) {\n URL.revokeObjectURL(workerBlobUrl);\n workerBlobUrl = null;\n }\n };\n\n if (signal) {\n if (signal.aborted) {\n cleanup();\n reject(new DOMException(\"Compression aborted\", \"AbortError\"));\n return;\n }\n signal.addEventListener(\n \"abort\",\n () => {\n cleanup();\n reject(new DOMException(\"Compression aborted\", \"AbortError\"));\n },\n { once: true },\n );\n }\n\n activeWorker.onmessage = (e) => {\n if (e.data.id !== id) return;\n cleanup();\n if (e.data.success) {\n resolve({\n blob: e.data.blob,\n width: e.data.width,\n height: e.data.height,\n });\n } else {\n reject(new Error(e.data.error || \"Worker compression failed\"));\n }\n };\n\n activeWorker.onerror = (err) => {\n cleanup();\n reject(new Error(err.message || \"Worker execution failed\"));\n };\n\n activeWorker.postMessage({\n id,\n blob,\n maxWidth,\n maxHeight,\n quality,\n mimeType,\n backgroundColor,\n });\n });\n } catch {\n // If CSP blocks blob: workers or Worker throws, fallback to main thread\n return compressWithMainThread(\n blob,\n maxWidth,\n maxHeight,\n quality,\n mimeType,\n backgroundColor,\n signal,\n );\n }\n}\n",
|
|
8
|
+
"import { compressWithMainThread } from \"./canvas\";\nimport { extractMetadataSegments, spliceMetadataIntoBlob } from \"./jpeg\";\nimport type { CompressionResult, CompressOptions } from \"./types\";\nimport { compressWithWorker } from \"./worker\";\n\nexport { compressWithMainThread } from \"./canvas\";\nexport {\n extractMetadataSegments,\n normalizeExifOrientation,\n spliceMetadataIntoBlob,\n} from \"./jpeg\";\nexport { compressWithWorker } from \"./worker\";\nexport type { CompressionResult, CompressOptions };\n\n/**\n * Compresses an image file or blob client-side.\n * Runs off the main thread in a Web Worker by default, preserving EXIF metadata and ICC color profiles for JPEGs.\n */\nexport async function compressImage(\n fileOrBlob: File | Blob,\n options: CompressOptions = {},\n): Promise<File | Blob> {\n // If running in SSR / Node environment without DOM/Worker APIs, pass through unchanged\n if (typeof window === \"undefined\" && typeof self === \"undefined\") {\n return fileOrBlob;\n }\n\n const {\n maxSizeMB = Number.POSITIVE_INFINITY,\n maxWidth,\n maxHeight,\n quality = 0.85,\n mimeType = (fileOrBlob.type as CompressOptions[\"mimeType\"]) || \"image/jpeg\",\n preserveMetadata = true,\n backgroundColor = \"#ffffff\",\n useWebWorker = true,\n signal,\n onProgress,\n } = options;\n\n if (signal?.aborted) {\n throw new DOMException(\"Compression aborted\", \"AbortError\");\n }\n\n const maxSizeBytes = maxSizeMB * 1024 * 1024;\n const isAlreadyWithinBounds =\n fileOrBlob.size <= maxSizeBytes &&\n !maxWidth &&\n !maxHeight &&\n (!fileOrBlob.type || fileOrBlob.type === mimeType);\n\n if (isAlreadyWithinBounds) {\n return fileOrBlob;\n }\n\n onProgress?.(10, \"Extracting metadata\");\n\n // 1. Extract metadata segments if JPEG\n let metadataSegments: Uint8Array[] = [];\n const isJpeg =\n fileOrBlob.type === \"image/jpeg\" ||\n (fileOrBlob instanceof File && /\\.(jpe?g)$/i.test(fileOrBlob.name));\n\n if (preserveMetadata && isJpeg && mimeType === \"image/jpeg\") {\n try {\n metadataSegments = await extractMetadataSegments(fileOrBlob);\n } catch {\n // Continue even if metadata extraction fails\n }\n }\n\n if (signal?.aborted)\n throw new DOMException(\"Compression aborted\", \"AbortError\");\n\n onProgress?.(30, \"Compressing pixels\");\n\n // 2. Perform compression pass (Worker or Main Thread)\n const runner = useWebWorker ? compressWithWorker : compressWithMainThread;\n let result = await runner(\n fileOrBlob,\n maxWidth,\n maxHeight,\n quality,\n mimeType,\n backgroundColor,\n signal,\n );\n\n // 3. Adaptive second pass if output still exceeds maxSizeBytes\n if (result.blob.size > maxSizeBytes) {\n onProgress?.(65, \"Optimizing file size\");\n const scaleRatio = Math.sqrt(maxSizeBytes / result.blob.size) * 0.95;\n const nextW = Math.max(\n 800,\n Math.round(result.width * Math.min(0.85, scaleRatio)),\n );\n const nextQ = Math.max(0.65, quality * 0.85);\n\n result = await runner(\n result.blob,\n nextW,\n undefined,\n nextQ,\n mimeType,\n backgroundColor,\n signal,\n );\n }\n\n if (signal?.aborted)\n throw new DOMException(\"Compression aborted\", \"AbortError\");\n\n onProgress?.(85, \"Preserving metadata\");\n\n // 4. Splice original EXIF & ICC segments into output JPEG\n let finalBlob = result.blob;\n if (metadataSegments.length > 0 && mimeType === \"image/jpeg\") {\n finalBlob = await spliceMetadataIntoBlob(finalBlob, metadataSegments);\n }\n\n onProgress?.(100, \"Complete\");\n\n // 5. If input was a File, preserve name and lastModified\n if (fileOrBlob instanceof File) {\n const ext =\n mimeType === \"image/webp\"\n ? \"webp\"\n : mimeType === \"image/png\"\n ? \"png\"\n : \"jpg\";\n const baseName = fileOrBlob.name.replace(/\\.[^/.]+$/, \"\") || \"photo\";\n return new File([finalBlob], `${baseName}.${ext}`, {\n type: mimeType,\n lastModified: fileOrBlob.lastModified,\n });\n }\n\n return finalBlob;\n}\n\nexport default compressImage;\n"
|
|
9
|
+
],
|
|
10
|
+
"mappings": "yvBAMO,eAAe,CAAsB,CAC1C,EACA,EACA,EACA,EACA,EACA,EACA,EAC4B,CAC5B,GAAI,GAAQ,QACV,MAAM,IAAI,aAAa,sBAAuB,YAAY,EAI5D,GACE,OAAO,gBAAoB,KAC3B,OAAO,kBAAsB,IAC7B,CACA,IAAI,EACJ,GAAI,CACF,EAAS,MAAM,kBAAkB,EAAM,CACrC,iBAAkB,YACpB,CAAC,EACD,KAAM,CACN,EAAS,MAAM,kBAAkB,CAAI,EAGvC,IAAI,EAAQ,EAAO,MACf,EAAS,EAAO,OAEpB,GAAI,GAAY,EAAQ,EACtB,EAAS,KAAK,MAAO,EAAS,EAAY,CAAK,EAC/C,EAAQ,EAEV,GAAI,GAAa,EAAS,EACxB,EAAQ,KAAK,MAAO,EAAQ,EAAa,CAAM,EAC/C,EAAS,EAGX,IAAM,EAAS,IAAI,gBAAgB,EAAO,CAAM,EAC1C,EAAM,EAAO,WAAW,IAAI,EAClC,GAAI,C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AK,MAAM,EAAO,MAAQ,KAAK,IAAI,KAAM,CAAU,CAAC,CACtD,EACM,EAAQ,KAAK,IAAI,KAAM,EAAU,IAAI,EAE3C,EAAS,MAAM,EACb,EAAO,KACP,EACA,OACA,EACA,EACA,EACA,CACF,EAGF,GAAI,GAAQ,QACV,MAAM,IAAI,aAAa,sBAAuB,YAAY,EAE5D,IAAa,GAAI,qBAAqB,EAGtC,IAAI,EAAY,EAAO,KACvB,GAAI,EAAiB,OAAS,GAAK,IAAa,aAC9C,EAAY,MAAM,EAAuB,EAAW,CAAgB,EAMtE,GAHA,IAAa,IAAK,UAAU,EAGxB,aAAsB,KAAM,CAC9B,IAAM,EACJ,IAAa,aACT,OACA,IAAa,YACX,MACA,MACF,EAAW,EAAW,KAAK,QAAQ,YAAa,EAAE,GAAK,QAC7D,OAAO,IAAI,KAAK,CAAC,CAAS,EAAG,GAAG,KAAY,IAAO,CACjD,KAAM,EACN,aAAc,EAAW,YAC3B,CAAC,EAGH,OAAO,EAGT,IAAe",
|
|
11
|
+
"debugId": "3BA6709284FC283864756E2164756E21",
|
|
12
|
+
"names": []
|
|
13
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { CompressionResult, CompressOptions } from "./types";
|
|
2
|
+
export { compressWithMainThread } from "./canvas";
|
|
3
|
+
export { extractMetadataSegments, normalizeExifOrientation, spliceMetadataIntoBlob, } from "./jpeg";
|
|
4
|
+
export { compressWithWorker } from "./worker";
|
|
5
|
+
export type { CompressionResult, CompressOptions };
|
|
6
|
+
/**
|
|
7
|
+
* Compresses an image file or blob client-side.
|
|
8
|
+
* Runs off the main thread in a Web Worker by default, preserving EXIF metadata and ICC color profiles for JPEGs.
|
|
9
|
+
*/
|
|
10
|
+
export declare function compressImage(fileOrBlob: File | Blob, options?: CompressOptions): Promise<File | Blob>;
|
|
11
|
+
export default compressImage;
|
|
12
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,iBAAiB,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAGlE,OAAO,EAAE,sBAAsB,EAAE,MAAM,UAAU,CAAC;AAClD,OAAO,EACL,uBAAuB,EACvB,wBAAwB,EACxB,sBAAsB,GACvB,MAAM,QAAQ,CAAC;AAChB,OAAO,EAAE,kBAAkB,EAAE,MAAM,UAAU,CAAC;AAC9C,YAAY,EAAE,iBAAiB,EAAE,eAAe,EAAE,CAAC;AAEnD;;;GAGG;AACH,wBAAsB,aAAa,CACjC,UAAU,EAAE,IAAI,GAAG,IAAI,EACvB,OAAO,GAAE,eAAoB,GAC5B,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC,CAqHtB;AAED,eAAe,aAAa,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
async function b(e,c,a,n,s,f,r){if(r?.aborted)throw new DOMException("Compression aborted","AbortError");if(typeof OffscreenCanvas<"u"&&typeof createImageBitmap<"u"){let o;try{o=await createImageBitmap(e,{imageOrientation:"from-image"})}catch{o=await createImageBitmap(e)}let t=o.width,i=o.height;if(c&&t>c)i=Math.round(i*c/t),t=c;if(a&&i>a)t=Math.round(t*a/i),i=a;let d=new OffscreenCanvas(t,i),u=d.getContext("2d");if(!u)throw Error("OffscreenCanvas 2D context unavailable");if(s==="image/jpeg"&&f)u.fillStyle=f,u.fillRect(0,0,t,i);return u.drawImage(o,0,0,t,i),o.close(),{blob:await d.convertToBlob({type:s,quality:n}),width:t,height:i}}return new Promise((o,t)=>{if(typeof window>"u"||typeof document>"u"){o({blob:e,width:0,height:0});return}let i=new Image,d=URL.createObjectURL(e),u=()=>{URL.revokeObjectURL(d),t(new DOMException("Compression aborted","AbortError"))};if(r){if(r.aborted)return u();r.addEventListener("abort",u,{once:!0})}i.onload=()=>{URL.revokeObjectURL(d);let{naturalWidth:p,naturalHeight:l}=i;if(c&&p>c)l=Math.round(l*c/p),p=c;if(a&&l>a)p=Math.round(p*a/l),l=a;let h=document.createElement("canvas");h.width=p,h.height=l;let m=h.getContext("2d");if(!m){t(Error("Canvas 2D context unavailable"));return}if(s==="image/jpeg"&&f)m.fillStyle=f,m.fillRect(0,0,p,l);m.drawImage(i,0,0,p,l),h.toBlob((w)=>{if(w)o({blob:w,width:p,height:l});else t(Error("Canvas compression failed to produce blob"))},s,n)},i.onerror=()=>{URL.revokeObjectURL(d),t(Error("Failed to load image for compression"))},i.src=d})}async function C(e){let c=Math.min(e.size,262144),a=await e.slice(0,c).arrayBuffer(),n=new DataView(a);if(n.byteLength<4||n.getUint16(0)!==65496)return[];let s=[],f=2;while(f+4<n.byteLength){let r=n.getUint16(f);if(r===65498||r===65497||(r&65280)!==65280)break;let o=n.getUint16(f+2);if(o<2||f+2+o>n.byteLength)break;if(r===65505||r===65506){let t=new Uint8Array(a.slice(f,f+2+o));v(t),s.push(t)}f+=2+o}return s}function v(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 a=10,n=new DataView(e.buffer,e.byteOffset,e.byteLength),s=n.getUint16(a)===18761;if(!s&&n.getUint16(a)!==19789)return!1;if(n.getUint16(a+2,s)!==42)return!1;let f=n.getUint32(a+4,s),r=a+f;if(r+2>e.length)return!1;let o=n.getUint16(r,s);for(let t=0;t<o;t++){let i=r+2+t*12;if(i+12>e.length)break;if(n.getUint16(i,s)===274)return n.setUint16(i+8,1,s),!0}return!1}async function E(e,c){if(c.length===0)return e;let a=await e.slice(0,32).arrayBuffer(),n=new DataView(a);if(n.byteLength<4||n.getUint16(0)!==65496)return e;let s=2;if(n.getUint16(2)===65504)s=4+n.getUint16(4);let f=e.slice(0,s),r=e.slice(s),o=c.map((t)=>t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength));return new Blob([f,...o,r],{type:e.type||"image/jpeg"})}var L=`
|
|
2
|
+
self.onmessage = async (e) => {
|
|
3
|
+
const { id, blob, maxWidth, maxHeight, quality, mimeType, backgroundColor } = e.data;
|
|
4
|
+
try {
|
|
5
|
+
let bitmap;
|
|
6
|
+
try {
|
|
7
|
+
bitmap = await createImageBitmap(blob, { imageOrientation: "from-image" });
|
|
8
|
+
} catch {
|
|
9
|
+
bitmap = await createImageBitmap(blob);
|
|
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
|
+
|
|
24
|
+
const canvas = new OffscreenCanvas(width, height);
|
|
25
|
+
const ctx = canvas.getContext("2d");
|
|
26
|
+
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
|
+
ctx.drawImage(bitmap, 0, 0, width, height);
|
|
34
|
+
bitmap.close();
|
|
35
|
+
|
|
36
|
+
const outputBlob = await canvas.convertToBlob({ type: mimeType, quality });
|
|
37
|
+
self.postMessage({ id, success: true, blob: outputBlob, width, height });
|
|
38
|
+
} catch (err) {
|
|
39
|
+
self.postMessage({ id, success: false, error: err?.message || String(err) });
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
`;async function U(e,c,a,n,s,f,r){if(typeof Worker>"u"||typeof OffscreenCanvas>"u")return b(e,c,a,n,s,f,r);let o=null;try{let t=new Blob([L],{type:"application/javascript"});o=URL.createObjectURL(t);let i=new Worker(o),d=i;return await new Promise((u,p)=>{let l=Math.random().toString(36).slice(2),h=()=>{if(d)d.terminate(),d=null;if(o)URL.revokeObjectURL(o),o=null};if(r){if(r.aborted){h(),p(new DOMException("Compression aborted","AbortError"));return}r.addEventListener("abort",()=>{h(),p(new DOMException("Compression aborted","AbortError"))},{once:!0})}i.onmessage=(m)=>{if(m.data.id!==l)return;if(h(),m.data.success)u({blob:m.data.blob,width:m.data.width,height:m.data.height});else p(Error(m.data.error||"Worker compression failed"))},i.onerror=(m)=>{h(),p(Error(m.message||"Worker execution failed"))},i.postMessage({id:l,blob:e,maxWidth:c,maxHeight:a,quality:n,mimeType:s,backgroundColor:f})})}catch{return b(e,c,a,n,s,f,r)}}async function I(e,c={}){if(typeof window>"u"&&typeof self>"u")return e;let{maxSizeMB:a=Number.POSITIVE_INFINITY,maxWidth:n,maxHeight:s,quality:f=0.85,mimeType:r=e.type||"image/jpeg",preserveMetadata:o=!0,backgroundColor:t="#ffffff",useWebWorker:i=!0,signal:d,onProgress:u}=c;if(d?.aborted)throw new DOMException("Compression aborted","AbortError");let p=a*1024*1024;if(e.size<=p&&!n&&!s&&(!e.type||e.type===r))return e;u?.(10,"Extracting metadata");let h=[],m=e.type==="image/jpeg"||e instanceof File&&/\.(jpe?g)$/i.test(e.name);if(o&&m&&r==="image/jpeg")try{h=await C(e)}catch{}if(d?.aborted)throw new DOMException("Compression aborted","AbortError");u?.(30,"Compressing pixels");let w=i?U:b,g=await w(e,n,s,f,r,t,d);if(g.blob.size>p){u?.(65,"Optimizing file size");let y=Math.sqrt(p/g.blob.size)*0.95,M=Math.max(800,Math.round(g.width*Math.min(0.85,y))),R=Math.max(0.65,f*0.85);g=await w(g.blob,M,void 0,R,r,t,d)}if(d?.aborted)throw new DOMException("Compression aborted","AbortError");u?.(85,"Preserving metadata");let x=g.blob;if(h.length>0&&r==="image/jpeg")x=await E(x,h);if(u?.(100,"Complete"),e instanceof File){let y=r==="image/webp"?"webp":r==="image/png"?"png":"jpg",M=e.name.replace(/\.[^/.]+$/,"")||"photo";return new File([x],`${M}.${y}`,{type:r,lastModified:e.lastModified})}return x}var F=I;export{I as compressImage,b as compressWithMainThread,U as compressWithWorker,F as default,C as extractMetadataSegments,v as normalizeExifOrientation,E as spliceMetadataIntoBlob};
|
|
43
|
+
|
|
44
|
+
//# debugId=2C66E8F58449DA0964756E2164756E21
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/canvas.ts", "../src/jpeg.ts", "../src/worker.ts", "../src/index.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import type { CompressionResult } from \"./types\";\n\n/**\n * Main-thread image compressor fallback.\n * Uses OffscreenCanvas if available, otherwise falls back to HTMLCanvasElement.\n */\nexport async function compressWithMainThread(\n blob: Blob,\n maxWidth: number | undefined,\n maxHeight: number | undefined,\n quality: number,\n mimeType: string,\n backgroundColor: string,\n signal?: AbortSignal,\n): Promise<CompressionResult> {\n if (signal?.aborted) {\n throw new DOMException(\"Compression aborted\", \"AbortError\");\n }\n\n // Fast path: use OffscreenCanvas on main thread if supported\n if (\n typeof OffscreenCanvas !== \"undefined\" &&\n typeof createImageBitmap !== \"undefined\"\n ) {\n let bitmap: ImageBitmap;\n try {\n bitmap = await createImageBitmap(blob, {\n imageOrientation: \"from-image\",\n });\n } catch {\n bitmap = await createImageBitmap(blob);\n }\n\n let width = bitmap.width;\n let height = bitmap.height;\n\n if (maxWidth && width > maxWidth) {\n height = Math.round((height * maxWidth) / width);\n width = maxWidth;\n }\n if (maxHeight && height > maxHeight) {\n width = Math.round((width * maxHeight) / height);\n height = maxHeight;\n }\n\n const canvas = new OffscreenCanvas(width, height);\n const ctx = canvas.getContext(\"2d\");\n if (!ctx) throw new Error(\"OffscreenCanvas 2D context unavailable\");\n\n if (mimeType === \"image/jpeg\" && backgroundColor) {\n ctx.fillStyle = backgroundColor;\n ctx.fillRect(0, 0, width, height);\n }\n\n ctx.drawImage(bitmap, 0, 0, width, height);\n bitmap.close();\n\n const outputBlob = await canvas.convertToBlob({ type: mimeType, quality });\n return { blob: outputBlob, width, height };\n }\n\n // Fallback: standard DOM HTMLCanvasElement\n return new Promise((resolve, reject) => {\n if (typeof window === \"undefined\" || typeof document === \"undefined\") {\n resolve({ blob, width: 0, height: 0 });\n return;\n }\n\n const img = new Image();\n const url = URL.createObjectURL(blob);\n\n const onAbort = () => {\n URL.revokeObjectURL(url);\n reject(new DOMException(\"Compression aborted\", \"AbortError\"));\n };\n\n if (signal) {\n if (signal.aborted) return onAbort();\n signal.addEventListener(\"abort\", onAbort, { once: true });\n }\n\n img.onload = () => {\n URL.revokeObjectURL(url);\n let width = img.naturalWidth;\n let height = img.naturalHeight;\n\n if (maxWidth && width > maxWidth) {\n height = Math.round((height * maxWidth) / width);\n width = maxWidth;\n }\n if (maxHeight && height > maxHeight) {\n width = Math.round((width * maxHeight) / height);\n height = maxHeight;\n }\n\n const canvas = document.createElement(\"canvas\");\n canvas.width = width;\n canvas.height = height;\n const ctx = canvas.getContext(\"2d\");\n if (!ctx) {\n reject(new Error(\"Canvas 2D context unavailable\"));\n return;\n }\n\n if (mimeType === \"image/jpeg\" && backgroundColor) {\n ctx.fillStyle = backgroundColor;\n ctx.fillRect(0, 0, width, height);\n }\n\n ctx.drawImage(img, 0, 0, width, height);\n\n canvas.toBlob(\n (resBlob) => {\n if (resBlob) resolve({ blob: resBlob, width, height });\n else reject(new Error(\"Canvas compression failed to produce blob\"));\n },\n mimeType,\n quality,\n );\n };\n\n img.onerror = () => {\n URL.revokeObjectURL(url);\n reject(new Error(\"Failed to load image for compression\"));\n };\n\n img.src = url;\n });\n}\n",
|
|
6
|
+
"/**\n * Extracts raw EXIF (APP1, 0xFFE1) and ICC Profile (APP2, 0xFFE2) metadata segments from a JPEG file.\n * Reads only the first 256 KB of the file, keeping memory usage minimal.\n */\nexport async function extractMetadataSegments(\n fileOrBlob: Blob,\n): Promise<Uint8Array[]> {\n const chunkSize = Math.min(fileOrBlob.size, 256 * 1024);\n const buffer = await fileOrBlob.slice(0, chunkSize).arrayBuffer();\n const view = new DataView(buffer);\n if (view.byteLength < 4 || view.getUint16(0) !== 0xffd8) return [];\n\n const segments: Uint8Array[] = [];\n let offset = 2;\n\n while (offset + 4 < view.byteLength) {\n const marker = view.getUint16(offset);\n // Stop at Start of Scan (SOS), End of Image (EOI), or invalid marker\n if (\n marker === 0xffda ||\n marker === 0xffd9 ||\n (marker & 0xff00) !== 0xff00\n ) {\n break;\n }\n\n const segLength = view.getUint16(offset + 2);\n if (segLength < 2 || offset + 2 + segLength > view.byteLength) break;\n\n // Preserve APP1 (0xFFE1: Exif / XMP) and APP2 (0xFFE2: ICC color profile)\n if (marker === 0xffe1 || marker === 0xffe2) {\n const segBytes = new Uint8Array(\n buffer.slice(offset, offset + 2 + segLength),\n );\n normalizeExifOrientation(segBytes);\n segments.push(segBytes);\n }\n\n offset += 2 + segLength;\n }\n\n return segments;\n}\n\n/**\n * Normalizes the EXIF Orientation tag to 1 (normal / top-left) in place.\n * Since modern browsers decode and draw upright on canvas (or via createImageBitmap),\n * resetting orientation to 1 prevents external photo viewers from rotating a second time.\n */\nexport function normalizeExifOrientation(segment: Uint8Array): boolean {\n if (segment.length < 14) return false;\n\n // Check for APP1 marker (0xFFE1) + length + 'Exif\\0\\0'\n const isExif =\n segment[0] === 0xff &&\n segment[1] === 0xe1 &&\n segment[4] === 0x45 && // 'E'\n segment[5] === 0x78 && // 'x'\n segment[6] === 0x69 && // 'i'\n segment[7] === 0x66 && // 'f'\n segment[8] === 0x00 &&\n segment[9] === 0x00;\n\n if (!isExif) return false;\n\n const tiffStart = 10;\n const view = new DataView(\n segment.buffer,\n segment.byteOffset,\n segment.byteLength,\n );\n\n const isLittleEndian = view.getUint16(tiffStart) === 0x4949; // 'II'\n if (!isLittleEndian && view.getUint16(tiffStart) !== 0x4d4d) return false; // 'MM'\n if (view.getUint16(tiffStart + 2, isLittleEndian) !== 0x002a) return false; // 42\n\n const firstIfdOffset = view.getUint32(tiffStart + 4, isLittleEndian);\n const ifdStart = tiffStart + firstIfdOffset;\n if (ifdStart + 2 > segment.length) return false;\n\n const tagCount = view.getUint16(ifdStart, isLittleEndian);\n for (let i = 0; i < tagCount; i++) {\n const entryOffset = ifdStart + 2 + i * 12;\n if (entryOffset + 12 > segment.length) break;\n\n const tagId = view.getUint16(entryOffset, isLittleEndian);\n if (tagId === 0x0112) {\n // Orientation tag: write 1 (SHORT = 3, count = 1)\n view.setUint16(entryOffset + 8, 1, isLittleEndian);\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Injects raw original metadata segments into the canvas-compressed JPEG blob.\n */\nexport async function spliceMetadataIntoBlob(\n compressedBlob: Blob,\n metadataSegments: Uint8Array[],\n): Promise<Blob> {\n if (metadataSegments.length === 0) return compressedBlob;\n\n const headBuffer = await compressedBlob.slice(0, 32).arrayBuffer();\n const headView = new DataView(headBuffer);\n if (headView.byteLength < 4 || headView.getUint16(0) !== 0xffd8) {\n return compressedBlob;\n }\n\n let startOffset = 2; // Right after SOI (0xFFD8)\n if (headView.getUint16(2) === 0xffe0) {\n const jfifLen = headView.getUint16(4);\n startOffset = 4 + jfifLen;\n }\n\n const headerPart = compressedBlob.slice(0, startOffset);\n const bodyPart = compressedBlob.slice(startOffset);\n const segmentBuffers: BlobPart[] = metadataSegments.map(\n (s) =>\n s.buffer.slice(s.byteOffset, s.byteOffset + s.byteLength) as ArrayBuffer,\n );\n\n return new Blob([headerPart, ...segmentBuffers, bodyPart], {\n type: compressedBlob.type || \"image/jpeg\",\n });\n}\n",
|
|
7
|
+
"import { compressWithMainThread } from \"./canvas\";\nimport type { CompressionResult } from \"./types\";\n\nconst WORKER_SCRIPT = `\nself.onmessage = async (e) => {\n const { id, blob, maxWidth, maxHeight, quality, mimeType, backgroundColor } = e.data;\n try {\n let bitmap;\n try {\n bitmap = await createImageBitmap(blob, { imageOrientation: \"from-image\" });\n } catch {\n bitmap = await createImageBitmap(blob);\n }\n\n let width = bitmap.width;\n let height = bitmap.height;\n\n if (maxWidth && width > maxWidth) {\n height = Math.round((height * maxWidth) / width);\n width = maxWidth;\n }\n if (maxHeight && height > maxHeight) {\n width = Math.round((width * maxHeight) / height);\n height = maxHeight;\n }\n\n const canvas = new OffscreenCanvas(width, height);\n const ctx = canvas.getContext(\"2d\");\n if (!ctx) throw new Error(\"OffscreenCanvas 2D context unavailable\");\n\n if (mimeType === \"image/jpeg\" && backgroundColor) {\n ctx.fillStyle = backgroundColor;\n ctx.fillRect(0, 0, width, height);\n }\n\n ctx.drawImage(bitmap, 0, 0, width, height);\n bitmap.close();\n\n const outputBlob = await canvas.convertToBlob({ type: mimeType, quality });\n self.postMessage({ id, success: true, blob: outputBlob, width, height });\n } catch (err) {\n self.postMessage({ id, success: false, error: err?.message || String(err) });\n }\n};\n`;\n\n/**\n * Runs image compression off the main thread in a Web Worker using createImageBitmap + OffscreenCanvas.\n * If Web Workers or OffscreenCanvas are blocked or unavailable, automatically falls back to main-thread processing.\n */\nexport async function compressWithWorker(\n blob: Blob,\n maxWidth: number | undefined,\n maxHeight: number | undefined,\n quality: number,\n mimeType: string,\n backgroundColor: string,\n signal?: AbortSignal,\n): Promise<CompressionResult> {\n // Graceful fallback if Web Worker or OffscreenCanvas is unavailable (e.g. older browser or strict environment)\n if (typeof Worker === \"undefined\" || typeof OffscreenCanvas === \"undefined\") {\n return compressWithMainThread(\n blob,\n maxWidth,\n maxHeight,\n quality,\n mimeType,\n backgroundColor,\n signal,\n );\n }\n\n let workerBlobUrl: string | null = null;\n\n try {\n const workerBlob = new Blob([WORKER_SCRIPT], {\n type: \"application/javascript\",\n });\n workerBlobUrl = URL.createObjectURL(workerBlob);\n const activeWorker = new Worker(workerBlobUrl);\n let workerRef: Worker | null = activeWorker;\n\n return await new Promise<CompressionResult>((resolve, reject) => {\n const id = Math.random().toString(36).slice(2);\n\n const cleanup = () => {\n if (workerRef) {\n workerRef.terminate();\n workerRef = null;\n }\n if (workerBlobUrl) {\n URL.revokeObjectURL(workerBlobUrl);\n workerBlobUrl = null;\n }\n };\n\n if (signal) {\n if (signal.aborted) {\n cleanup();\n reject(new DOMException(\"Compression aborted\", \"AbortError\"));\n return;\n }\n signal.addEventListener(\n \"abort\",\n () => {\n cleanup();\n reject(new DOMException(\"Compression aborted\", \"AbortError\"));\n },\n { once: true },\n );\n }\n\n activeWorker.onmessage = (e) => {\n if (e.data.id !== id) return;\n cleanup();\n if (e.data.success) {\n resolve({\n blob: e.data.blob,\n width: e.data.width,\n height: e.data.height,\n });\n } else {\n reject(new Error(e.data.error || \"Worker compression failed\"));\n }\n };\n\n activeWorker.onerror = (err) => {\n cleanup();\n reject(new Error(err.message || \"Worker execution failed\"));\n };\n\n activeWorker.postMessage({\n id,\n blob,\n maxWidth,\n maxHeight,\n quality,\n mimeType,\n backgroundColor,\n });\n });\n } catch {\n // If CSP blocks blob: workers or Worker throws, fallback to main thread\n return compressWithMainThread(\n blob,\n maxWidth,\n maxHeight,\n quality,\n mimeType,\n backgroundColor,\n signal,\n );\n }\n}\n",
|
|
8
|
+
"import { compressWithMainThread } from \"./canvas\";\nimport { extractMetadataSegments, spliceMetadataIntoBlob } from \"./jpeg\";\nimport type { CompressionResult, CompressOptions } from \"./types\";\nimport { compressWithWorker } from \"./worker\";\n\nexport { compressWithMainThread } from \"./canvas\";\nexport {\n extractMetadataSegments,\n normalizeExifOrientation,\n spliceMetadataIntoBlob,\n} from \"./jpeg\";\nexport { compressWithWorker } from \"./worker\";\nexport type { CompressionResult, CompressOptions };\n\n/**\n * Compresses an image file or blob client-side.\n * Runs off the main thread in a Web Worker by default, preserving EXIF metadata and ICC color profiles for JPEGs.\n */\nexport async function compressImage(\n fileOrBlob: File | Blob,\n options: CompressOptions = {},\n): Promise<File | Blob> {\n // If running in SSR / Node environment without DOM/Worker APIs, pass through unchanged\n if (typeof window === \"undefined\" && typeof self === \"undefined\") {\n return fileOrBlob;\n }\n\n const {\n maxSizeMB = Number.POSITIVE_INFINITY,\n maxWidth,\n maxHeight,\n quality = 0.85,\n mimeType = (fileOrBlob.type as CompressOptions[\"mimeType\"]) || \"image/jpeg\",\n preserveMetadata = true,\n backgroundColor = \"#ffffff\",\n useWebWorker = true,\n signal,\n onProgress,\n } = options;\n\n if (signal?.aborted) {\n throw new DOMException(\"Compression aborted\", \"AbortError\");\n }\n\n const maxSizeBytes = maxSizeMB * 1024 * 1024;\n const isAlreadyWithinBounds =\n fileOrBlob.size <= maxSizeBytes &&\n !maxWidth &&\n !maxHeight &&\n (!fileOrBlob.type || fileOrBlob.type === mimeType);\n\n if (isAlreadyWithinBounds) {\n return fileOrBlob;\n }\n\n onProgress?.(10, \"Extracting metadata\");\n\n // 1. Extract metadata segments if JPEG\n let metadataSegments: Uint8Array[] = [];\n const isJpeg =\n fileOrBlob.type === \"image/jpeg\" ||\n (fileOrBlob instanceof File && /\\.(jpe?g)$/i.test(fileOrBlob.name));\n\n if (preserveMetadata && isJpeg && mimeType === \"image/jpeg\") {\n try {\n metadataSegments = await extractMetadataSegments(fileOrBlob);\n } catch {\n // Continue even if metadata extraction fails\n }\n }\n\n if (signal?.aborted)\n throw new DOMException(\"Compression aborted\", \"AbortError\");\n\n onProgress?.(30, \"Compressing pixels\");\n\n // 2. Perform compression pass (Worker or Main Thread)\n const runner = useWebWorker ? compressWithWorker : compressWithMainThread;\n let result = await runner(\n fileOrBlob,\n maxWidth,\n maxHeight,\n quality,\n mimeType,\n backgroundColor,\n signal,\n );\n\n // 3. Adaptive second pass if output still exceeds maxSizeBytes\n if (result.blob.size > maxSizeBytes) {\n onProgress?.(65, \"Optimizing file size\");\n const scaleRatio = Math.sqrt(maxSizeBytes / result.blob.size) * 0.95;\n const nextW = Math.max(\n 800,\n Math.round(result.width * Math.min(0.85, scaleRatio)),\n );\n const nextQ = Math.max(0.65, quality * 0.85);\n\n result = await runner(\n result.blob,\n nextW,\n undefined,\n nextQ,\n mimeType,\n backgroundColor,\n signal,\n );\n }\n\n if (signal?.aborted)\n throw new DOMException(\"Compression aborted\", \"AbortError\");\n\n onProgress?.(85, \"Preserving metadata\");\n\n // 4. Splice original EXIF & ICC segments into output JPEG\n let finalBlob = result.blob;\n if (metadataSegments.length > 0 && mimeType === \"image/jpeg\") {\n finalBlob = await spliceMetadataIntoBlob(finalBlob, metadataSegments);\n }\n\n onProgress?.(100, \"Complete\");\n\n // 5. If input was a File, preserve name and lastModified\n if (fileOrBlob instanceof File) {\n const ext =\n mimeType === \"image/webp\"\n ? \"webp\"\n : mimeType === \"image/png\"\n ? \"png\"\n : \"jpg\";\n const baseName = fileOrBlob.name.replace(/\\.[^/.]+$/, \"\") || \"photo\";\n return new File([finalBlob], `${baseName}.${ext}`, {\n type: mimeType,\n lastModified: fileOrBlob.lastModified,\n });\n }\n\n return finalBlob;\n}\n\nexport default compressImage;\n"
|
|
9
|
+
],
|
|
10
|
+
"mappings": "AAMO,eAAe,CAAsB,CAC1C,EACA,EACA,EACA,EACA,EACA,EACA,EAC4B,CAC5B,GAAI,GAAQ,QACV,MAAM,IAAI,aAAa,sBAAuB,YAAY,EAI5D,GACE,OAAO,gBAAoB,KAC3B,OAAO,kBAAsB,IAC7B,CACA,IAAI,EACJ,GAAI,CACF,EAAS,MAAM,kBAAkB,EAAM,CACrC,iBAAkB,YACpB,CAAC,EACD,KAAM,CACN,EAAS,MAAM,kBAAkB,CAAI,EAGvC,IAAI,EAAQ,EAAO,MACf,EAAS,EAAO,OAEpB,GAAI,GAAY,EAAQ,EACtB,EAAS,KAAK,MAAO,EAAS,EAAY,CAAK,EAC/C,EAAQ,EAEV,GAAI,GAAa,EAAS,EACxB,EAAQ,KAAK,MAAO,EAAQ,EAAa,CAAM,EAC/C,EAAS,EAGX,IAAM,EAAS,IAAI,gBAAgB,EAAO,CAAM,EAC1C,EAAM,EAAO,WAAW,IAAI,EAClC,GAAI,CAAC,EAAK,MAAU,MAAM,wCAAwC,EAElE,GAAI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AAU,CAAC,CACtD,EACM,EAAQ,KAAK,IAAI,KAAM,EAAU,IAAI,EAE3C,EAAS,MAAM,EACb,EAAO,KACP,EACA,OACA,EACA,EACA,EACA,CACF,EAGF,GAAI,GAAQ,QACV,MAAM,IAAI,aAAa,sBAAuB,YAAY,EAE5D,IAAa,GAAI,qBAAqB,EAGtC,IAAI,EAAY,EAAO,KACvB,GAAI,EAAiB,OAAS,GAAK,IAAa,aAC9C,EAAY,MAAM,EAAuB,EAAW,CAAgB,EAMtE,GAHA,IAAa,IAAK,UAAU,EAGxB,aAAsB,KAAM,CAC9B,IAAM,EACJ,IAAa,aACT,OACA,IAAa,YACX,MACA,MACF,EAAW,EAAW,KAAK,QAAQ,YAAa,EAAE,GAAK,QAC7D,OAAO,IAAI,KAAK,CAAC,CAAS,EAAG,GAAG,KAAY,IAAO,CACjD,KAAM,EACN,aAAc,EAAW,YAC3B,CAAC,EAGH,OAAO,EAGT,IAAe",
|
|
11
|
+
"debugId": "2C66E8F58449DA0964756E2164756E21",
|
|
12
|
+
"names": []
|
|
13
|
+
}
|
package/dist/jpeg.d.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Extracts raw EXIF (APP1, 0xFFE1) and ICC Profile (APP2, 0xFFE2) metadata segments from a JPEG file.
|
|
3
|
+
* Reads only the first 256 KB of the file, keeping memory usage minimal.
|
|
4
|
+
*/
|
|
5
|
+
export declare function extractMetadataSegments(fileOrBlob: Blob): Promise<Uint8Array[]>;
|
|
6
|
+
/**
|
|
7
|
+
* Normalizes the EXIF Orientation tag to 1 (normal / top-left) in place.
|
|
8
|
+
* Since modern browsers decode and draw upright on canvas (or via createImageBitmap),
|
|
9
|
+
* resetting orientation to 1 prevents external photo viewers from rotating a second time.
|
|
10
|
+
*/
|
|
11
|
+
export declare function normalizeExifOrientation(segment: Uint8Array): boolean;
|
|
12
|
+
/**
|
|
13
|
+
* Injects raw original metadata segments into the canvas-compressed JPEG blob.
|
|
14
|
+
*/
|
|
15
|
+
export declare function spliceMetadataIntoBlob(compressedBlob: Blob, metadataSegments: Uint8Array[]): Promise<Blob>;
|
|
16
|
+
//# sourceMappingURL=jpeg.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"jpeg.d.ts","sourceRoot":"","sources":["../src/jpeg.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,wBAAsB,uBAAuB,CAC3C,UAAU,EAAE,IAAI,GACf,OAAO,CAAC,UAAU,EAAE,CAAC,CAoCvB;AAED;;;;GAIG;AACH,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,UAAU,GAAG,OAAO,CA6CrE;AAED;;GAEG;AACH,wBAAsB,sBAAsB,CAC1C,cAAc,EAAE,IAAI,EACpB,gBAAgB,EAAE,UAAU,EAAE,GAC7B,OAAO,CAAC,IAAI,CAAC,CAyBf"}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
export interface CompressOptions {
|
|
2
|
+
/** Target maximum output file size in megabytes (e.g. 1 for 1 MB). If omitted, compression is governed by quality and dimensions without a hard megabyte ceiling. */
|
|
3
|
+
maxSizeMB?: number;
|
|
4
|
+
/** Maximum width in pixels. Proportional downscaling preserves aspect ratio. */
|
|
5
|
+
maxWidth?: number;
|
|
6
|
+
/** Maximum height in pixels. Proportional downscaling preserves aspect ratio. */
|
|
7
|
+
maxHeight?: number;
|
|
8
|
+
/** Compression quality between 0.0 and 1.0. Default: 0.85 */
|
|
9
|
+
quality?: number;
|
|
10
|
+
/** Output MIME type. Default: input file type, or 'image/jpeg' if input type is not supported. */
|
|
11
|
+
mimeType?: "image/jpeg" | "image/webp" | "image/png";
|
|
12
|
+
/** Whether to preserve JPEG EXIF (camera, lens, ISO) and ICC color profile (Display P3). Default: true */
|
|
13
|
+
preserveMetadata?: boolean;
|
|
14
|
+
/** Background color fill when converting images with transparency to JPEG. Default: '#ffffff' */
|
|
15
|
+
backgroundColor?: string;
|
|
16
|
+
/** Whether to run compression off the main thread in a Web Worker. Default: true */
|
|
17
|
+
useWebWorker?: boolean;
|
|
18
|
+
/** AbortSignal to cancel compression. */
|
|
19
|
+
signal?: AbortSignal;
|
|
20
|
+
/** Progress notification callback (progress: 0 to 100, stage: descriptive phase). */
|
|
21
|
+
onProgress?: (progress: number, stage: string) => void;
|
|
22
|
+
}
|
|
23
|
+
export interface CompressionResult {
|
|
24
|
+
blob: Blob;
|
|
25
|
+
width: number;
|
|
26
|
+
height: number;
|
|
27
|
+
}
|
|
28
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,eAAe;IAC9B,qKAAqK;IACrK,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,gFAAgF;IAChF,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,iFAAiF;IACjF,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,6DAA6D;IAC7D,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,kGAAkG;IAClG,QAAQ,CAAC,EAAE,YAAY,GAAG,YAAY,GAAG,WAAW,CAAC;IACrD,0GAA0G;IAC1G,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,iGAAiG;IACjG,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,oFAAoF;IACpF,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,yCAAyC;IACzC,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,qFAAqF;IACrF,UAAU,CAAC,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;CACxD;AAED,MAAM,WAAW,iBAAiB;IAChC,IAAI,EAAE,IAAI,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;CAChB"}
|
package/dist/worker.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { CompressionResult } from "./types";
|
|
2
|
+
/**
|
|
3
|
+
* Runs image compression off the main thread in a Web Worker using createImageBitmap + OffscreenCanvas.
|
|
4
|
+
* If Web Workers or OffscreenCanvas are blocked or unavailable, automatically falls back to main-thread processing.
|
|
5
|
+
*/
|
|
6
|
+
export declare function compressWithWorker(blob: Blob, maxWidth: number | undefined, maxHeight: number | undefined, quality: number, mimeType: string, backgroundColor: string, signal?: AbortSignal): Promise<CompressionResult>;
|
|
7
|
+
//# sourceMappingURL=worker.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"worker.d.ts","sourceRoot":"","sources":["../src/worker.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAC;AA6CjD;;;GAGG;AACH,wBAAsB,kBAAkB,CACtC,IAAI,EAAE,IAAI,EACV,QAAQ,EAAE,MAAM,GAAG,SAAS,EAC5B,SAAS,EAAE,MAAM,GAAG,SAAS,EAC7B,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,MAAM,EAChB,eAAe,EAAE,MAAM,EACvB,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,iBAAiB,CAAC,CA+F5B"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,55 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "imagepressor",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "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.",
|
|
5
|
+
"main": "./dist/index.cjs",
|
|
6
|
+
"module": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.js",
|
|
12
|
+
"require": "./dist/index.cjs"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"dist",
|
|
17
|
+
"README.md",
|
|
18
|
+
"LICENSE"
|
|
19
|
+
],
|
|
20
|
+
"scripts": {
|
|
21
|
+
"build": "bun run build.ts",
|
|
22
|
+
"test": "bun test"
|
|
23
|
+
},
|
|
24
|
+
"keywords": [
|
|
25
|
+
"imagepressor",
|
|
26
|
+
"image-compressor",
|
|
27
|
+
"image-compression",
|
|
28
|
+
"browser-image-compression",
|
|
29
|
+
"client-side",
|
|
30
|
+
"web-worker",
|
|
31
|
+
"offscreen-canvas",
|
|
32
|
+
"exif",
|
|
33
|
+
"icc-profile",
|
|
34
|
+
"display-p3",
|
|
35
|
+
"zero-dependency",
|
|
36
|
+
"bun"
|
|
37
|
+
],
|
|
38
|
+
"author": {
|
|
39
|
+
"name": "Jai",
|
|
40
|
+
"url": "https://github.com/ijaik"
|
|
41
|
+
},
|
|
42
|
+
"license": "MIT",
|
|
43
|
+
"repository": {
|
|
44
|
+
"type": "git",
|
|
45
|
+
"url": "git+https://github.com/ijaik/imagepressor.git"
|
|
46
|
+
},
|
|
47
|
+
"homepage": "https://github.com/ijaik/imagepressor#readme",
|
|
48
|
+
"bugs": {
|
|
49
|
+
"url": "https://github.com/ijaik/imagepressor/issues"
|
|
50
|
+
},
|
|
51
|
+
"devDependencies": {
|
|
52
|
+
"@types/bun": "1.4.4",
|
|
53
|
+
"typescript": "5.9.3"
|
|
54
|
+
}
|
|
55
|
+
}
|