-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
231 lines (206 loc) · 6.38 KB
/
index.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
import { encode } from "fast-png";
import { get, set } from "idb-keyval";
import { GIFExtractor } from "./lib/gif";
import {
isFileSystemAPISupported,
attachFileDrop,
verifyPermission,
} from "./lib/util";
const $ = document.querySelector.bind(document);
if (!isFileSystemAPISupported()) {
$(".not-supported").style.display = "";
$(".content").style.display = "none";
} else {
setup();
}
async function setup() {
let dir;
let gifFiles = [];
const dropper = $(".dropper");
const extractBtn = $(".extract");
const status = $(".status");
addPlaceholder();
const oldDir = await get("dir");
if (oldDir) {
setDir(oldDir);
}
$(".outdir-select").onclick = (ev) => {
ev.preventDefault();
try {
selectDir();
} catch (err) {
showError(err);
}
};
extractBtn.onclick = async (ev) => {
ev.preventDefault();
if (!dir) return showError("Need to select a directory first");
const verified = await verifyPermission(dir, true);
if (verified) {
await extract();
} else {
showError("Only works if permission is granted.");
}
};
const sizeSelect = $(".size-select");
const sizeInputContainer = $(".size-input-container");
const sizeInput = $(".size-input");
let scaleMode = "none";
sizeSelect.oninput = (ev) => {
scaleMode = sizeSelect.options[sizeSelect.selectedIndex].value;
sizeInputContainer.style.display = scaleMode === "none" ? "none" : "";
};
attachFileDrop({
container: document.body,
async onDrop(files) {
gifFiles = files;
clearElement(dropper);
updateButtonState();
if (gifFiles.length > 0) {
for (let file of gifFiles) {
const image = await readAsImage(file);
dropper.appendChild(image);
}
} else {
addPlaceholder();
}
},
});
function clearElement(el) {
while (el.lastElementChild) {
el.removeChild(el.lastElementChild);
}
}
function addPlaceholder() {
const span = document.createElement("span");
span.classList.add("dropper-content");
span.textContent = `Drag & Drop your GIF files onto this page...`;
dropper.appendChild(span);
return span;
}
async function extract() {
status.textContent = "Reading...";
for (let file of gifFiles) {
const buf = await readAsBuffer(file);
const dirOutName = file.name.replace(/\.(gif)$/i, "");
const outDir = await dir.getDirectoryHandle(dirOutName, { create: true });
for (let frame of GIFExtractor(buf)) {
const { data, width, height, channels, name, frameIndex, totalFrames } =
frame;
status.textContent = `Extracting ${dirOutName}: ${
frameIndex + 1
} / ${totalFrames}`;
const aspect = width / height;
let newWidth = width,
newHeight = height;
if (scaleMode === "width") {
newWidth = parseInt(sizeInput.value, 10) || width;
newHeight = Math.floor(newWidth / aspect);
} else if (scaleMode === "height") {
newHeight = parseInt(sizeInput.value, 10) || height;
newWidth = Math.floor(newHeight * aspect);
}
const resizedData =
newWidth == width && newHeight == height
? data
: resize(data, width, height, newWidth, newHeight);
const enc = encode({
data: resizedData,
width: newWidth,
height: newHeight,
channels,
depth: 8,
});
const fh = await outDir.getFileHandle(name, { create: true });
const fw = await fh.createWritable();
fw.write(enc);
fw.close();
}
}
status.textContent = `Done. Check your output folder!`;
}
function showError(error) {
if (typeof error !== "string") error = error.message || "unknown error";
const errStr = `Error: ${error}`;
alert(errStr);
}
function updateButtonState() {
if (dir && gifFiles.length > 0) {
extractBtn.removeAttribute("disabled");
}
}
async function selectDir() {
try {
dir = await window.showDirectoryPicker({
mode: "readwrite",
});
setDir(dir);
} catch (err) {
if (err.code === 20 || err.name === "AbortError") {
// don't warn on abort
return null;
} else {
throw err;
}
}
}
async function setDir(dirHandle) {
dir = dirHandle;
if (!dir || dir.kind !== "directory") throw new Error("expected directory");
$(".outdir-name").textContent = dir.name;
await set("dir", dir);
updateButtonState();
}
}
async function readAsImage(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
const data = reader.result;
const image = new Image();
image.onload = () => resolve(image);
image.onerror = () =>
reject(new Error(`could not load image file ${file.name}`));
image.crossOrigin = "Anonymous";
image.src = data;
};
reader.onerror = () =>
reject(new Error(`could not read file ${file.name}`));
reader.readAsDataURL(file);
});
}
async function readAsBuffer(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
const data = reader.result;
resolve(data);
};
reader.onerror = () =>
reject(new Error(`could not read file ${file.name}`));
reader.readAsArrayBuffer(file);
});
}
function resize(rgba, srcWidth, srcHeight, dstWidth, dstHeight) {
// Create a new Uint8Array to hold the resized image data
const out = new Uint8ClampedArray(dstWidth * dstHeight * 4);
// Calculate the ratio of the old width/height to the new width/height
const xRatio = srcWidth / dstWidth;
const yRatio = srcHeight / dstHeight;
for (let dstY = 0; dstY < dstHeight; dstY++) {
for (let dstX = 0; dstX < dstWidth; dstX++) {
// Find the nearest neighbor in the source image
const srcX = Math.min(Math.round(dstX * xRatio), srcWidth - 1);
const srcY = Math.min(Math.round(dstY * yRatio), srcHeight - 1);
// Calculate the index in the one-dimensional image arrays
const srcIndex = (srcY * srcWidth + srcX) * 4;
const dstIndex = (dstY * dstWidth + dstX) * 4;
// Copy the pixel data from the source to the destination
for (let i = 0; i < 4; i++) {
// RGBA has 4 components
out[dstIndex + i] = rgba[srcIndex + i];
}
}
}
return out;
}