Skip to content

Commit 8060dea

Browse files
authored
Merge pull request #13 from Lenni009/dev
copy file to worker instead of transfer
2 parents e86e92f + 9cb474e commit 8060dea

File tree

9 files changed

+71
-34
lines changed

9 files changed

+71
-34
lines changed

.github/workflows/publish-npm.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@ jobs:
3232
run: |
3333
npm ci
3434
npm run build
35+
cd dist
36+
mv simple-image-compressor.umd.cjs simple-image-compressor-min.js
3537
3638
- name: Publish to NPM
3739
run: npm publish

README.md

Lines changed: 49 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,33 +6,44 @@ Greatly inspired by https://github.com/WangYuLue/image-conversion
66

77
## Installation
88

9+
### NPM
10+
911
```sh
1012
npm i simple-image-compressor
1113
```
1214

15+
### CDN
16+
17+
```html
18+
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/simple-image-compressor.js"></script>
19+
```
20+
1321
## Main function
1422

1523
`compressImage()`
1624

1725
## Parameters
1826

1927
1. file: File
20-
2. config: `{ type: 'image/png' | 'image/jpeg' | 'image/gif' = 'image/jpeg', quality: number = 0.92 }`
28+
2. config: `{ type: 'image/jpeg' | 'image/webp' = 'image/jpeg', quality: number = 0.92 }`
2129

2230
## Return
2331

2432
`Promise<Blob>`
2533

2634
## Usage
2735

28-
```ts
36+
### NPM
37+
38+
```js
2939
import { compressImage } from 'simple-image-compressor';
3040

3141
async function compressFile(file) {
32-
const res = await compressImage(file, {
42+
const options = {
3343
quality: 0.9,
3444
type: 'image/jpeg',
35-
});
45+
};
46+
const res = await compressImage(file, options);
3647
return new File([res], 'new filename.jpg', { type: 'image/jpeg' });
3748
}
3849

@@ -43,19 +54,50 @@ const compressedImage = await compressFile(file);
4354
// upload to server, etc.
4455
```
4556
57+
### CDN
58+
59+
```html
60+
<html lang="en">
61+
<head>
62+
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/simple-image-compressor.js"></script>
63+
<script>
64+
window.onload = () => {
65+
const fileInput = document.getElementById('file-input');
66+
fileInput.addEventListener('change', async () => {
67+
const file = fileInput.files[0];
68+
const options = {
69+
quality: 0.9,
70+
type: imageCompressor.imageTypes.WEBP,
71+
};
72+
const compressedImage = await imageCompressor.compressImage(file, options);
73+
// do something with the compressed image
74+
});
75+
};
76+
</script>
77+
</head>
78+
79+
<body>
80+
<input
81+
id="file-input"
82+
type="file"
83+
/>
84+
</body>
85+
</html>
86+
```
87+
4688
### Additional Export
4789
48-
```ts
90+
```js
4991
import { imageTypes, compressImage } from 'simple-image-compressor';
5092
```
5193
5294
`imageTypes` is an object containing the two expected values for `config.type`:
5395
54-
```ts
96+
```js
5597
const imageTypes = {
5698
WEBP: 'image/webp',
5799
JPEG: 'image/jpeg',
58-
}
100+
};
59101
```
60102
61103
## How it works

package-lock.json

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
{
22
"name": "simple-image-compressor",
3-
"version": "1.5.0",
3+
"version": "1.7.0",
44
"type": "module",
55
"description": "Simple frontend JS library to compress images",
6-
"main": "./dist/index.js",
6+
"main": "./dist/simple-image-compressor.js",
77
"types": "./dist/index.d.ts",
88
"files": [
99
"dist"

src/main.ts

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,8 @@ export async function compressImage(file: File, config: CompressionConfig = {}):
1818
...config,
1919
};
2020

21-
const buffer = await file.arrayBuffer();
22-
2321
// construct object to send to worker
24-
const workerMessage: WorkerMessage = { buffer, img: { width, height }, config: workerConfig };
22+
const workerMessage: WorkerMessage = { file, img: { width, height }, config: workerConfig };
2523

2624
// let the worker process the file
2725
const compressedBlob = await handleWorkerProcess(workerMessage);

src/types.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,19 +15,19 @@ export interface WorkerMessageConfig extends CompressionConfig {
1515

1616
export interface WorkerMessage {
1717
img: { width: number; height: number };
18-
buffer: ArrayBuffer;
18+
file: File;
1919
config: WorkerMessageConfig;
2020
}
2121

2222
type Status = 'success' | 'error';
23-
type WorkerData = ArrayBuffer | string;
23+
type WorkerData = Blob | string;
2424

2525
interface GenericWorkerResponse<T extends Status, U extends WorkerData> {
2626
status: T;
2727
data: U;
2828
}
2929

30-
export type WorkerSuccessResponse = GenericWorkerResponse<'success', ArrayBuffer>;
30+
export type WorkerSuccessResponse = GenericWorkerResponse<'success', Blob>;
3131
export type WorkerErrorResponse = GenericWorkerResponse<'error', string>;
3232

3333
export type WorkerResponse = WorkerSuccessResponse | WorkerErrorResponse;

src/worker.ts

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,11 @@ import type { WorkerErrorResponse, WorkerMessage, WorkerSuccessResponse } from '
33
onmessage = async ({ data }: MessageEvent<WorkerMessage>) => {
44
try {
55
const workerResult = await compressFileWorker(data);
6-
const buffer = await workerResult.arrayBuffer();
76
const transferObject: WorkerSuccessResponse = {
87
status: 'success',
9-
data: buffer,
8+
data: workerResult,
109
};
11-
postMessage(transferObject, { transfer: [transferObject.data] });
10+
postMessage(transferObject);
1211
} catch (error) {
1312
const errorMessage = `Could not compress! ${error instanceof Error ? error.message : ''}`;
1413
const transferObject: WorkerErrorResponse = {
@@ -21,15 +20,13 @@ onmessage = async ({ data }: MessageEvent<WorkerMessage>) => {
2120
}
2221
};
2322

24-
async function compressFileWorker({ img: { width, height }, buffer, config }: WorkerMessage) {
23+
async function compressFileWorker({ img: { width, height }, file, config }: WorkerMessage) {
2524
// Create an OffscreenCanvas
2625
const offscreenCanvas = new OffscreenCanvas(width, height);
2726
const ctx = offscreenCanvas.getContext('2d');
2827

29-
const blob = new Blob([buffer], { type: config.originalType });
30-
31-
// Create an ImageBitmap from the blob
32-
const imageBitmap = await createImageBitmap(blob);
28+
// Create an ImageBitmap from the file
29+
const imageBitmap = await createImageBitmap(file);
3330

3431
// Draw the ImageBitmap onto the OffscreenCanvas
3532
ctx?.drawImage(imageBitmap, 0, 0);

src/workerHandler.ts

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,17 +7,15 @@ export async function handleWorkerProcess(workerMessage: WorkerMessage) {
77
const worker = new ImageWorker();
88

99
// Send the object URL to the worker
10-
worker.postMessage(workerMessage, [workerMessage.buffer]);
10+
worker.postMessage(workerMessage);
1111

1212
worker.onmessage = ({ data }: MessageEvent<WorkerResponse>) => {
1313
if (data.status === 'error') {
1414
console.error(data.data);
1515
reject(data.data); // Reject the promise if there's an error
1616
} else {
17-
const file = new Blob([data.data], {
18-
type: workerMessage.config.type,
19-
});
20-
resolve(file); // Resolve the promise with the data from the worker
17+
const blob = data.data;
18+
resolve(blob); // Resolve the promise with the data from the worker
2119
}
2220
};
2321
});

vite.config.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,19 +7,19 @@ export default defineConfig({
77
base: './',
88
plugins: [
99
dts({
10+
exclude: ['**/**.spec.*', '**/**.test.*', '*.config.*'],
1011
insertTypesEntry: true,
1112
}),
1213
],
1314
worker: {
14-
format: 'es'
15+
format: 'es',
1516
},
1617
build: {
1718
lib: {
1819
// Could also be a dictionary or array of multiple entry points
1920
entry: fileURLToPath(new URL('src/main.ts', import.meta.url)),
20-
fileName: 'index',
21-
name: 'simple-image-compressor',
22-
formats: ['es'],
21+
name: 'imageCompressor',
22+
formats: ['es', 'umd'],
2323
},
2424
},
2525
});

0 commit comments

Comments
 (0)