-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathmain.js
83 lines (74 loc) · 2.55 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import * as avif from 'https://unpkg.com/@jsquash/avif@latest?module';
import * as jpeg from 'https://unpkg.com/@jsquash/jpeg@latest?module';
import * as jxl from 'https://unpkg.com/@jsquash/jxl@latest?module';
import * as png from 'https://unpkg.com/@jsquash/png@latest?module';
import * as webp from 'https://unpkg.com/@jsquash/webp@latest?module';
async function decode (sourceType, fileBuffer) {
switch (sourceType) {
case 'avif':
return await avif.decode(fileBuffer);
case 'jpeg':
return await jpeg.decode(fileBuffer);
case 'jxl':
return await jxl.decode(fileBuffer);
case 'png':
return await png.decode(fileBuffer);
case 'webp':
return await webp.decode(fileBuffer);
default:
throw new Error(`Unknown source type: ${sourceType}`);
}
}
async function encode (outputType, imageData) {
switch (outputType) {
case 'avif':
return await avif.encode(imageData);
case 'jpeg':
return await jpeg.encode(imageData);
case 'jxl':
return await jxl.encode(imageData);
case 'png':
return await png.encode(imageData);
case 'webp':
return await webp.encode(imageData);
default:
throw new Error(`Unknown output type: ${outputType}`);
}
}
async function convert (sourceType, outputType, fileBuffer) {
const imageData = await decode(sourceType, fileBuffer);
return encode(outputType, imageData);
}
function blobToBase64(blob) {
return new Promise((resolve, _) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result);
reader.readAsDataURL(blob);
});
}
async function showOutput (imageBuffer, outputType) {
const preview = document.querySelector('#preview');
const imageBlob = new Blob([imageBuffer], { type: `image/${outputType}` });
const base64String = await blobToBase64(imageBlob);
const previewImg = document.createElement('img');
previewImg.src = base64String;
preview.innerHTML = '';
preview.appendChild(previewImg);
}
async function initForm () {
const form = document.querySelector('form');
form.addEventListener('submit', async (event) => {
event.preventDefault();
const formData = new FormData(form);
const file = formData.get('file');
const sourceType = file.name.endsWith('jxl') ? 'jxl' : file.type.replace('image/', '');
const outputType = formData.get('outputType');
const fileBuffer = await file.arrayBuffer();
const imageBuffer = await convert(sourceType, outputType, fileBuffer);
showOutput(imageBuffer, outputType);
});
}
async function main () {
initForm();
}
main();