Repository navigation
Expand file tree
/
Copy pathimage-resizer.html
More file actions
1228 lines (1150 loc) Β· 66.7 KB
/
Copy pathimage-resizer.html
File metadata and controls
1228 lines (1150 loc) Β· 66.7 KB
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<include src="_partials/meta-base.html"></include>
<title>Image Resizer β HTML Tools</title>
<meta name="description" content="Batch-resize images by percentage, exact size, or max dimensions β social-card presets, zip download. Runs in your browser, no installs, no tracking.">
<link rel="canonical" href="https://tools.mazipan.space/image-resizer">
<meta property="og:title" content="Image Resizer β HTML Tools">
<meta property="og:description" content="Batch-resize images by percentage, exact size, or max dimensions β social-card presets, zip download. Runs in your browser, no installs, no tracking.">
<meta property="og:url" content="https://tools.mazipan.space/image-resizer">
<meta name="twitter:title" content="Image Resizer β HTML Tools">
<meta name="twitter:description" content="Batch-resize images by percentage, exact size, or max dimensions β social-card presets, zip download. Runs in your browser, no installs, no tracking.">
<include src="_partials/meta-social.html"></include>
<link rel="icon" type="image/png" sizes="32x32" href="favicon-image-resizer.png">
<include src="_partials/head-fonts.html"></include>
<link rel="stylesheet" href="styles.css">
<style>
.row-card {
display: grid;
grid-template-columns: 56px minmax(0, 1fr);
gap: 0.6rem 0.75rem;
align-items: center;
padding: 0.65rem 0.85rem;
border: 1px solid #1f2937;
border-radius: 0.6rem;
background: rgba(17, 24, 39, 0.55);
}
.row-card:hover { border-color: #374151; }
.row-card .thumb {
width: 56px;
height: 56px;
border-radius: 0.4rem;
background: #0b1220;
object-fit: cover;
border: 1px solid #1f2937;
}
.row-card .row-stats { line-height: 1.35; }
.row-card .row-actions {
display: flex;
gap: 0.4rem;
grid-column: 1 / -1;
justify-self: end;
}
@media (min-width: 640px) {
.row-card { grid-template-columns: 56px minmax(0, 1fr) auto; }
.row-card .row-actions { grid-column: auto; justify-self: auto; }
}
.summary-bar {
position: sticky;
top: 0;
z-index: 5;
background: rgba(3, 7, 18, 0.92);
backdrop-filter: blur(6px);
border: 1px solid #1f2937;
border-radius: 0.65rem;
padding: 0.6rem 0.9rem;
margin-bottom: 0.75rem;
}
.mode-panel { display: none; }
.mode-panel.on { display: block; }
/* Single-file mode β wide card with a hero preview or a diff-slider compare. */
.single-card {
border: 1px solid #1f2937;
border-radius: 0.7rem;
background: rgba(17, 24, 39, 0.55);
padding: 1rem;
}
.single-card .preview-area {
display: block;
max-width: 100%;
max-height: 480px;
margin: 0 auto 0.9rem;
border-radius: 0.5rem;
border: 1px solid #1f2937;
background: #0b1220;
/* aspect-ratio set inline per item */
}
.single-card .diff-wrap.preview-area {
/* Keep diff-wrap's own checker background for transparency previews. */
background:
linear-gradient(45deg, #1f2937 25%, transparent 25%),
linear-gradient(-45deg, #1f2937 25%, transparent 25%),
linear-gradient(45deg, transparent 75%, #1f2937 75%),
linear-gradient(-45deg, transparent 75%, #1f2937 75%);
background-size: 16px 16px;
background-position: 0 0, 0 8px, 8px -8px, -8px 0;
}
.single-stats { line-height: 1.4; margin-bottom: 0.8rem; }
.single-actions { display: flex; flex-wrap: wrap; gap: 0.5rem; }
</style>
<include src="_partials/head-theme.html"></include>
<!-- BEGIN:json-ld generated by scripts/generate-sections.mjs β re-run after editing tools.json -->
<script type="application/ld+json">{"@context":"https://schema.org","@type":"WebApplication","name":"Image Resizer","url":"https://tools.mazipan.space/image-resizer","description":"Batch-resize images by percentage, exact size, or max dimensions β social-card presets, zip download. Runs in your browser, no installs, no tracking.","applicationCategory":"DeveloperApplication","operatingSystem":"Any","browserRequirements":"Requires JavaScript","offers":{"@type":"Offer","price":"0","priceCurrency":"USD"},"isPartOf":{"@type":"WebSite","name":"HTML Tools","url":"https://tools.mazipan.space/"}}</script>
<script type="application/ld+json">{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"HTML Tools","item":"https://tools.mazipan.space/"},{"@type":"ListItem","position":2,"name":"Image Resizer","item":"https://tools.mazipan.space/image-resizer"}]}</script>
<script type="application/ld+json">{"@context":"https://schema.org","@type":"FAQPage","mainEntity":[{"@type":"Question","name":"Does my image ever leave my computer?","acceptedAnswer":{"@type":"Answer","text":"No. Everything runs locally in your browser β decoding, resizing, and encoding all happen on-device via a Web Worker."}},{"@type":"Question","name":"What's the difference between Percentage, Exact, and Max?","acceptedAnswer":{"@type":"Answer","text":"Percentage scales every image by the same factor β quick \"halve everything\" workflows. Exact forces every output to a specific W Γ H and center-crops to fill β useful for social cards (OG 1200Γ630, Twitter 1600Γ900, etc.). Max caps the longer side while keeping the source aspect β good for blog images where you want \"max 1600px wide\" without distorting."}},{"@type":"Question","name":"What does Lock aspect ratio do?","acceptedAnswer":{"@type":"Answer","text":"In Max mode it preserves the source's aspect while fitting inside your max W Γ max H. In Exact mode it captures the current W:H when toggled on β editing one dimension then auto-fills the other so the captured ratio stays constant. Default is on in both modes."}},{"@type":"Question","name":"Will the resizer upscale a small image?","acceptedAnswer":{"@type":"Answer","text":"Max and Percentage modes are shrink-only β they never produce output larger than the source (Percentage's slider caps at 100% for the same reason). Exact mode returns whatever W Γ H you set, including dimensions larger than the source β the result will just look fuzzier."}},{"@type":"Question","name":"Where did the presets go?","acceptedAnswer":{"@type":"Answer","text":"Presets (OG 1200Γ630, Twitter 1600Γ900, Half, Quarter, Thumb 256) only appear when Lock aspect ratio is off in Max or Exact mode β they set explicit dimensions, which would otherwise silently violate the locked ratio. Percentage mode is implicitly always locked, so presets don't appear there."}},{"@type":"Question","name":"Can I download all my resized images at once?","acceptedAnswer":{"@type":"Answer","text":"Yes. The Download all (zip) button packs every output into a single store-only zip β unpacking is instant. Each row's Download button gets a single file."}},{"@type":"Question","name":"Why are some files marked 'kept original'?","acceptedAnswer":{"@type":"Answer","text":"If the source is already at or below the target and the format isn't changing, we skip the re-encode so you don't lose quality for no benefit. The file goes into the zip verbatim."}}]}</script>
<!-- END:json-ld -->
</head>
<body class="bg-gray-950 text-gray-200 min-h-screen flex flex-col">
<header class="border-b border-gray-800 px-6 py-4">
<nav aria-label="Breadcrumb" class="max-w-[1200px] mx-auto flex items-center gap-3">
<a href="index.html" class="no-underline text-white font-bold text-lg tracking-tight hover:text-blue-400 transition-colors">HTML Tools</a>
<span class="text-gray-700">/</span>
<span class="text-gray-400 text-sm flex items-center gap-1.5" aria-current="page">π Image Resizer</span>
</nav>
</header>
<main class="max-w-[1200px] mx-auto w-full flex-1 py-8 px-6">
<header class="mb-7">
<h1 class="text-3xl font-bold text-white flex items-center gap-3">π Image Resizer</h1>
<p class="mt-1.5 text-sm text-gray-500">Resize PNG, JPEG, WebP, and AVIF images locally β max dimensions, exact size, or percentage. Batch-friendly with social-card presets.</p>
</header>
<!-- Drop zone -->
<div id="drop" class="drop-zone p-8 mb-5 text-center" tabindex="0" role="button" aria-label="Drop images here, or click to choose files">
<div id="drop-empty">
<div class="text-3xl mb-2" aria-hidden="true">π</div>
<p class="text-sm text-gray-300 font-medium">Drop image(s) here, click to choose, or paste with Ctrl/Cmd+V</p>
<p class="text-xs text-gray-500 mt-1.5">Accepts PNG, JPEG, WebP, AVIF, BMP β up to 100 files</p>
</div>
<div id="drop-compact" class="hidden text-xs text-gray-500">+ Drop more Β· click Β· paste</div>
</div>
<input id="file-input" type="file" accept="image/*" multiple class="hidden">
<div id="error-bar" class="hidden error-bar mb-4"></div>
<!-- Controls -->
<section id="controls" class="hidden border border-gray-800 rounded-xl bg-gray-900/40 p-5 mb-5">
<!-- Output decisions (top β what comes out) -->
<div class="grid gap-5 md:grid-cols-2">
<div id="format-wrap">
<label class="block text-xs font-semibold text-gray-500 uppercase tracking-wide mb-2">Output format</label>
<div class="flex flex-wrap gap-1.5">
<button class="pill" data-format="same" type="button">Same as input</button>
<button class="pill" data-format="png" type="button">PNG</button>
<button class="pill" data-format="jpeg" type="button">JPEG</button>
<button class="pill" data-format="webp" type="button">WebP</button>
</div>
<p id="format-note" class="text-[0.7rem] text-gray-600 mt-1.5"></p>
</div>
<div id="quality-wrap">
<div class="flex items-center justify-between mb-2">
<label class="text-xs font-semibold text-gray-500 uppercase tracking-wide" for="quality">Quality</label>
<span id="quality-val" class="text-xs text-gray-400 font-mono">0.92</span>
</div>
<input id="quality" type="range" min="0.30" max="1.00" step="0.01" value="0.92" class="range" aria-label="Output quality">
<p class="text-[0.7rem] text-gray-600 mt-1.5">Lossy formats only β the slider is hidden when the output is PNG.</p>
</div>
<div class="min-w-0 md:col-span-2">
<label class="block text-xs font-semibold text-gray-500 uppercase tracking-wide mb-2" for="filename-pattern">Filename pattern</label>
<select id="filename-pattern" class="select w-full">
<option value="{name}.{ext}">{name}.{ext}</option>
<option value="{name}-{w}x{h}.{ext}">{name}-{w}x{h}.{ext}</option>
<option value="{name}-resized.{ext}">{name}-resized.{ext}</option>
<option value="{name}-{scale}.{ext}">{name}-{scale}.{ext}</option>
</select>
<p class="text-[0.7rem] text-gray-600 mt-1.5">Default <code>{name}.{ext}</code> reuses the source filename (overwrites on download if the source is in your Downloads folder).</p>
</div>
</div>
<!-- Mode toggle -->
<div class="mt-5 pt-4 border-t border-gray-800">
<label class="block text-xs font-semibold text-gray-500 uppercase tracking-wide mb-2">Resize mode</label>
<div role="radiogroup" aria-label="Resize mode" class="flex flex-wrap gap-1.5">
<button class="pill" data-mode="percent" type="button" role="radio">Percentage</button>
<button class="pill" data-mode="exact" type="button" role="radio">Exact dimensions</button>
<button class="pill" data-mode="max" type="button" role="radio">Max dimensions</button>
</div>
</div>
<!-- Percent mode panel -->
<div class="mode-panel mt-4" data-panel="percent">
<div>
<div class="flex items-center justify-between mb-2">
<label class="text-xs font-semibold text-gray-500 uppercase tracking-wide" for="scale">Scale</label>
<span id="scale-val" class="text-xs text-gray-400 font-mono">50%</span>
</div>
<input id="scale" type="range" min="10" max="100" step="5" value="50" class="range" aria-label="Scale percentage">
<p class="text-[0.7rem] text-gray-600 mt-1.5">Percentage mode is shrink-only β use Exact mode for explicit larger dimensions.</p>
</div>
</div>
<!-- Exact mode panel -->
<div class="mode-panel mt-4" data-panel="exact">
<label class="block text-xs font-semibold text-gray-500 uppercase tracking-wide mb-2">Target size</label>
<div class="flex items-center gap-2 text-sm text-gray-400 flex-wrap">
W <input id="exact-w" type="number" min="1" max="20000" value="1200" class="num-input" aria-label="Target width in pixels">
<span>Γ</span>
H <input id="exact-h" type="number" min="1" max="20000" value="630" class="num-input" aria-label="Target height in pixels">
</div>
<label class="switch mt-2.5"><input id="exact-lock-aspect" type="checkbox" checked><span>Lock aspect ratio</span></label>
<p class="text-[0.7rem] text-gray-600 mt-1">When on, editing one dimension auto-fills the other so the ratio captured at toggle-on stays constant. Source is always cropped from the center to fill the target.</p>
</div>
<!-- Max mode panel -->
<div class="mode-panel mt-4" data-panel="max">
<label class="block text-xs font-semibold text-gray-500 uppercase tracking-wide mb-2">Limits (leave blank to skip an axis)</label>
<div class="flex items-center gap-2 text-sm text-gray-400 flex-wrap">
max W <input id="max-w" type="number" min="1" max="20000" value="1600" class="num-input" aria-label="Max width in pixels">
<span>Γ</span>
max H <input id="max-h" type="number" min="1" max="20000" value="1600" class="num-input" aria-label="Max height in pixels">
</div>
<label class="switch mt-2.5"><input id="max-keep-aspect" type="checkbox" checked><span>Lock aspect ratio</span></label>
<p class="text-[0.7rem] text-gray-600 mt-1">When off, the image stretches to fill max W Γ max H exactly β rarely what you want. Output never exceeds the source resolution.</p>
</div>
<!-- Presets β only visible when the user has opted out of aspect-locking
(a preset would otherwise silently violate the locked ratio). -->
<section id="presets-section" class="mt-4 hidden">
<label class="block text-xs font-semibold text-gray-500 uppercase tracking-wide mb-2">Presets</label>
<div class="flex flex-wrap gap-1.5">
<button class="pill" data-preset="og" type="button">OG 1200Γ630</button>
<button class="pill" data-preset="twitter" type="button">Twitter 1600Γ900</button>
<button class="pill" data-preset="facebook" type="button">Facebook 1200Γ630</button>
<button class="pill" data-preset="linkedin" type="button">LinkedIn 1200Γ627</button>
<button class="pill" data-preset="pinterest" type="button">Pinterest 1000Γ1500</button>
<button class="pill" data-preset="half" type="button">Half</button>
<button class="pill" data-preset="quarter" type="button">Quarter</button>
<button class="pill" data-preset="thumb256" type="button">Thumb 256</button>
</div>
</section>
<div class="flex flex-wrap items-center gap-2 mt-5 pt-4 border-t border-gray-800">
<button id="resize-btn" class="btn btn-secondary" type="button">π Resize all</button>
<button id="zip-btn" class="btn btn-primary" type="button" disabled>π¦ Download all (zip)</button>
<button id="clear-btn" class="btn btn-danger" type="button">ποΈ Clear</button>
<span id="status" class="ml-auto text-xs text-gray-600" aria-live="polite"></span>
</div>
</section>
<!-- Summary bar -->
<div id="summary-bar" class="summary-bar hidden stats text-gray-300" aria-live="polite"></div>
<!-- File list -->
<section id="files" class="flex flex-col gap-2"></section>
</main>
<script src="image-utils.js"></script>
<script type="module">
const dropEl = document.getElementById('drop');
const dropEmpty = document.getElementById('drop-empty');
const dropCompact = document.getElementById('drop-compact');
const fileInput = document.getElementById('file-input');
const controlsEl = document.getElementById('controls');
const filesEl = document.getElementById('files');
const errorBar = document.getElementById('error-bar');
const statusEl = document.getElementById('status');
const summaryBar = document.getElementById('summary-bar');
const qualityEl = document.getElementById('quality');
const qualityVal = document.getElementById('quality-val');
const qualityWrap = document.getElementById('quality-wrap');
const formatWrap = document.getElementById('format-wrap');
const formatNote = document.getElementById('format-note');
const filenameSel = document.getElementById('filename-pattern');
const resizeBtn = document.getElementById('resize-btn');
const zipBtn = document.getElementById('zip-btn');
const clearBtn = document.getElementById('clear-btn');
const maxW = document.getElementById('max-w');
const maxH = document.getElementById('max-h');
const maxKeepAspect = document.getElementById('max-keep-aspect');
const exactW = document.getElementById('exact-w');
const exactH = document.getElementById('exact-h');
const exactLockAspect = document.getElementById('exact-lock-aspect');
const scaleEl = document.getElementById('scale');
const scaleVal = document.getElementById('scale-val');
const presetsSection = document.getElementById('presets-section');
const support = {
png: supportsMime('image/png'),
jpeg: supportsMime('image/jpeg'),
webp: supportsMime('image/webp'),
};
const HARD_CAP = 100;
const SOFT_WARN = 50;
// Upscaling is never useful (it just produces a fuzzier copy), so the
// worker / computeTargetSize defaults are relied on β no `noUpscale`
// toggle is exposed. Percent slider is capped at 100% for the same
// reason; for explicit larger dims the user goes to Exact mode.
// Aspect lock defaults ON everywhere β max keeps the source aspect, exact
// keeps whatever W:H the user last set. Presets are only shown when the
// user explicitly opts out of locking.
const settings = {
mode: 'percent',
max: { maxW: 1600, maxH: 1600, keepAspect: true },
exact: { targetW: 1200, targetH: 630, lockAspect: true, lockRatio: 1200 / 630 },
percent:{ scale: 50 },
format: 'same',
quality: 0.92,
pattern: '{name}.{ext}',
};
/** @type {Array<{id:string,file:File,name:string,srcMime:string,srcSize:number,srcW:number,srcH:number,srcUrl:string,dstBlob:Blob|null,dstUrl:string|null,dstW:number,dstH:number,dstName:string,kept:boolean,error:string|null,encoding:boolean}>} */
const items = [];
let nextId = 1;
// ββ Worker ββββββββββββββββββββββββββββββββββββββββββββββββββββ
const worker = new Worker(new URL('./image-encode-worker.js', import.meta.url), { type: 'module' });
const pending = new Map();
let nextJobId = 1;
worker.onmessage = (e) => {
const job = pending.get(e.data.id);
if (!job) return;
pending.delete(e.data.id);
if (e.data.error) job.reject(new Error(e.data.error));
else job.resolve(e.data);
};
worker.onerror = (e) => {
showError(`Worker error: ${e.message || 'unknown'}`);
};
function workerEncode(file, opts) {
const id = `j${nextJobId++}`;
return new Promise((resolve, reject) => {
pending.set(id, { resolve, reject });
worker.postMessage({ id, file, opts });
});
}
// ββ Mode panels βββββββββββββββββββββββββββββββββββββββββββββββ
function syncModePills() {
document.querySelectorAll('.pill[data-mode]').forEach(p => {
p.classList.toggle('on', p.dataset.mode === settings.mode);
p.setAttribute('aria-checked', p.dataset.mode === settings.mode ? 'true' : 'false');
});
document.querySelectorAll('.mode-panel').forEach(panel => {
panel.classList.toggle('on', panel.dataset.panel === settings.mode);
});
syncPresetsVisibility();
}
// Presets are an "escape hatch" for setting explicit dimensions β visible
// only when the user has opted out of aspect-locking in the current mode.
// Percent mode is implicitly always locked (uniform scale), so presets
// stay hidden there.
function syncPresetsVisibility() {
const unlockedMax = settings.mode === 'max' && !settings.max.keepAspect;
const unlockedExact = settings.mode === 'exact' && !settings.exact.lockAspect;
presetsSection.classList.toggle('hidden', !(unlockedMax || unlockedExact));
}
document.querySelectorAll('.pill[data-mode]').forEach(p => {
p.addEventListener('click', () => {
settings.mode = p.dataset.mode;
syncModePills();
scheduleResize();
});
});
// ββ Max mode controls βββββββββββββββββββββββββββββββββββββββββ
maxW.addEventListener('change', () => { settings.max.maxW = clampInt(maxW.value, 1, 20000); scheduleResize(); });
maxH.addEventListener('change', () => { settings.max.maxH = clampInt(maxH.value, 1, 20000); scheduleResize(); });
maxKeepAspect.addEventListener('change', () => {
settings.max.keepAspect = maxKeepAspect.checked;
syncPresetsVisibility();
scheduleResize();
});
// ββ Exact mode controls βββββββββββββββββββββββββββββββββββββββ
exactW.addEventListener('change', () => {
const newW = clampInt(exactW.value, 1, 20000);
if (settings.exact.lockAspect && settings.exact.lockRatio > 0) {
const newH = Math.max(1, Math.round(newW / settings.exact.lockRatio));
settings.exact.targetH = newH;
exactH.value = newH;
}
settings.exact.targetW = newW;
scheduleResize();
});
exactH.addEventListener('change', () => {
const newH = clampInt(exactH.value, 1, 20000);
if (settings.exact.lockAspect && settings.exact.lockRatio > 0) {
const newW = Math.max(1, Math.round(newH * settings.exact.lockRatio));
settings.exact.targetW = newW;
exactW.value = newW;
}
settings.exact.targetH = newH;
scheduleResize();
});
exactLockAspect.addEventListener('change', () => {
settings.exact.lockAspect = exactLockAspect.checked;
// Capture the current W:H as the ratio to preserve from here on.
if (settings.exact.lockAspect && settings.exact.targetW > 0 && settings.exact.targetH > 0) {
settings.exact.lockRatio = settings.exact.targetW / settings.exact.targetH;
}
syncPresetsVisibility();
});
// Fit is hardcoded to `cover` β the encoder always crops from the
// center to fill the target. The contain / stretch / background-color
// controls were removed because they're not what people reach for in
// typical "resize to these dimensions" workflows. If letterbox-with-bg
// is genuinely needed, the converter still exposes background, and Max
// mode + Lock aspect ratio + a larger box approximates the contain case.
// ββ Percent mode controls βββββββββββββββββββββββββββββββββββββ
scaleEl.addEventListener('input', () => {
const v = parseInt(scaleEl.value, 10) || 0;
settings.percent.scale = v;
scaleVal.textContent = `${v}%`;
});
scaleEl.addEventListener('change', () => scheduleResize());
// ββ Presets βββββββββββββββββββββββββββββββββββββββββββββββββββ
const PRESETS = {
og: { mode: 'exact', exact: { targetW: 1200, targetH: 630, fit: 'cover' } },
twitter: { mode: 'exact', exact: { targetW: 1600, targetH: 900, fit: 'cover' } },
facebook: { mode: 'exact', exact: { targetW: 1200, targetH: 630, fit: 'cover' } },
linkedin: { mode: 'exact', exact: { targetW: 1200, targetH: 627, fit: 'cover' } },
pinterest: { mode: 'exact', exact: { targetW: 1000, targetH: 1500, fit: 'cover' } },
half: { mode: 'percent', percent: { scale: 50 } },
quarter: { mode: 'percent', percent: { scale: 25 } },
thumb256: { mode: 'max', max: { maxW: 256, maxH: 256, keepAspect: true } },
};
document.querySelectorAll('.pill[data-preset]').forEach(p => {
p.addEventListener('click', () => applyPreset(p.dataset.preset));
});
function applyPreset(key) {
const preset = PRESETS[key];
if (!preset) return;
settings.mode = preset.mode;
if (preset.max) Object.assign(settings.max, preset.max);
if (preset.exact) Object.assign(settings.exact, preset.exact);
if (preset.percent) Object.assign(settings.percent, preset.percent);
// If lock-aspect is on in Exact mode, the captured ratio should track
// whatever the preset sets β otherwise the next W/H edit would snap
// back to the previously-locked ratio.
if (settings.exact.lockAspect && settings.exact.targetW > 0 && settings.exact.targetH > 0) {
settings.exact.lockRatio = settings.exact.targetW / settings.exact.targetH;
}
pushSettingsToUi();
syncModePills();
scheduleResize();
}
function pushSettingsToUi() {
maxW.value = settings.max.maxW;
maxH.value = settings.max.maxH;
maxKeepAspect.checked = settings.max.keepAspect;
exactW.value = settings.exact.targetW;
exactH.value = settings.exact.targetH;
exactLockAspect.checked = settings.exact.lockAspect;
scaleEl.value = String(settings.percent.scale);
scaleVal.textContent = `${settings.percent.scale}%`;
}
// ββ Output format / quality / filename ββββββββββββββββββββββββ
function syncFormatPills() {
document.querySelectorAll('.pill[data-format]').forEach(p => {
const f = p.dataset.format;
const ok = f === 'same' || support[f];
p.disabled = !ok;
p.classList.toggle('on', settings.format === f);
p.title = ok ? '' : `Your browser can't encode ${f.toUpperCase()}.`;
});
const resolved = resolveFormatLabel();
const lossless = resolved === 'png';
// Hide the quality column entirely when the resolved output is lossless,
// and let the format column span both grid tracks so the layout stays
// balanced on md+.
qualityWrap.classList.toggle('hidden', lossless);
formatWrap.classList.toggle('md:col-span-2', lossless);
formatNote.textContent = settings.format === 'same'
? 'Each file is re-encoded in its source format (PNG, JPEG, or WebP). GIF/BMP/AVIF sources fall back to PNG.'
: '';
}
function resolveFormatLabel() {
if (settings.format !== 'same') return settings.format;
// "Same" β if all items share a format, show it; otherwise show "mixed".
const fmts = new Set(items.map(i => inferFormat(i.srcMime)));
if (fmts.size === 1) return [...fmts][0];
return fmts.has('png') ? 'png' : 'jpeg';
}
document.querySelectorAll('.pill[data-format]').forEach(p => {
p.addEventListener('click', () => {
if (p.disabled) return;
settings.format = p.dataset.format;
syncFormatPills();
scheduleResize();
});
});
qualityEl.addEventListener('input', () => {
settings.quality = parseFloat(qualityEl.value);
qualityVal.textContent = settings.quality.toFixed(2);
});
qualityEl.addEventListener('change', () => scheduleResize());
filenameSel.addEventListener('change', () => {
settings.pattern = filenameSel.value;
renderAllCards();
});
// ββ Format resolution per-file ββββββββββββββββββββββββββββββββ
function inferFormat(mime) {
if (mime === 'image/png') return 'png';
if (mime === 'image/jpeg') return 'jpeg';
if (mime === 'image/webp') return 'webp';
return 'png';
}
function resolveFormatFor(item) {
return settings.format === 'same' ? inferFormat(item.srcMime) : settings.format;
}
// ββ Build opts for a single item ββββββββββββββββββββββββββββββ
function buildOpts(item) {
const format = resolveFormatFor(item);
const base = { enabled: true, mode: settings.mode, format, quality: settings.quality };
// noUpscale defaults to true in computeTargetSize when omitted, which
// matches the always-on behaviour we want.
if (settings.mode === 'max') {
Object.assign(base, {
maxW: settings.max.maxW,
maxH: settings.max.maxH,
keepAspect: settings.max.keepAspect,
});
} else if (settings.mode === 'exact') {
Object.assign(base, {
targetW: settings.exact.targetW,
targetH: settings.exact.targetH,
fit: 'cover', // resizer always center-crops to the target; worker handles JPEG-on-alpha bg internally
});
} else {
Object.assign(base, { scale: settings.percent.scale });
}
return base;
}
// ββ Action buttons ββββββββββββββββββββββββββββββββββββββββββββ
resizeBtn.addEventListener('click', () => resizeAll());
clearBtn.addEventListener('click', () => clearAll());
zipBtn.addEventListener('click', () => downloadZip());
// ββ Drop zone βββββββββββββββββββββββββββββββββββββββββββββββββ
['dragenter', 'dragover'].forEach(evt => {
dropEl.addEventListener(evt, e => { e.preventDefault(); dropEl.classList.add('dragover'); });
});
['dragleave', 'drop'].forEach(evt => {
dropEl.addEventListener(evt, e => {
e.preventDefault();
if (evt === 'dragleave' && dropEl.contains(e.relatedTarget)) return;
dropEl.classList.remove('dragover');
});
});
dropEl.addEventListener('drop', e => {
const files = [...(e.dataTransfer?.files || [])];
if (files.length) addFiles(files);
});
dropEl.addEventListener('click', () => fileInput.click());
dropEl.addEventListener('keydown', e => {
if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); fileInput.click(); }
});
fileInput.addEventListener('change', () => {
if (fileInput.files?.length) addFiles([...fileInput.files]);
fileInput.value = '';
});
window.addEventListener('paste', e => {
const list = [...(e.clipboardData?.items || [])];
const pasted = list.filter(i => i.type.startsWith('image/')).map(i => i.getAsFile()).filter(Boolean);
if (pasted.length) addFiles(pasted);
});
// ββ Add files βββββββββββββββββββββββββββββββββββββββββββββββββ
async function addFiles(rawFiles) {
const imgFiles = rawFiles.filter(f => f.type.startsWith('image/'));
const remaining = HARD_CAP - items.length;
const toAdd = imgFiles.slice(0, Math.max(0, remaining));
const dropped = rawFiles.length - imgFiles.length;
const overflow = imgFiles.length - toAdd.length;
const messages = [];
if (dropped) messages.push(`${dropped} non-image file${dropped === 1 ? '' : 's'} skipped`);
if (overflow) messages.push(`${overflow} file${overflow === 1 ? '' : 's'} skipped (cap is ${HARD_CAP})`);
if (messages.length) showError(messages.join(' Β· ')); else clearError();
controlsEl.classList.remove('hidden');
summaryBar.classList.remove('hidden');
dropEmpty.classList.add('hidden');
dropCompact.classList.remove('hidden');
dropEl.classList.add('compact', 'p-3');
dropEl.classList.remove('p-8');
if (items.length + toAdd.length > SOFT_WARN) {
statusEl.textContent = `Large batch β encoding may take a moment.`;
}
const probeQueue = [];
for (const file of toAdd) {
const id = `f${nextId++}`;
const item = {
id, file, name: file.name,
srcMime: file.type, srcSize: file.size,
srcW: 0, srcH: 0,
srcUrl: URL.createObjectURL(file),
dstBlob: null, dstUrl: null, dstW: 0, dstH: 0,
dstName: file.name,
kept: false, error: null, encoding: true,
};
items.push(item);
probeQueue.push(probeAndEncode(item));
}
// Render everything in the loop's *final* count so the layout picks the
// right template (the first dropped file briefly rendered as a single
// card before the next one arrives β re-render so they're consistent).
renderAllCards();
updateSummary();
syncFormatPills();
await Promise.all(probeQueue);
statusEl.textContent = '';
}
async function probeAndEncode(item) {
// Decode once on the page to learn dimensions; the worker re-decodes
// for the actual encode (no need to keep an ImageBitmap alive across
// postMessage trips and re-runs).
try {
const bm = await createImageBitmap(item.file, { imageOrientation: 'from-image' });
item.srcW = bm.width;
item.srcH = bm.height;
bm.close?.();
} catch (err) {
item.error = `Decode failed: ${err.message || err}`;
item.encoding = false;
renderCard(item);
updateSummary();
return;
}
await encodeOne(item);
updateSummary();
}
// ββ Encoding ββββββββββββββββββββββββββββββββββββββββββββββββββ
async function encodeOne(item) {
item.encoding = true;
item.error = null;
renderCard(item);
const opts = buildOpts(item);
const { w: dstW, h: dstH } = computeTargetSize(item.srcW, item.srcH, opts);
const format = resolveFormatFor(item);
const noResize = dstW === item.srcW && dstH === item.srcH;
// "Kept original" path: no resize, no format change β reuse the
// source File so we don't re-encode for no benefit.
const formatMatchesSource =
settings.format === 'same' && inferFormat(item.srcMime) === format && item.srcMime === FORMAT_MIME[format];
if (noResize && formatMatchesSource) {
if (item.dstUrl) URL.revokeObjectURL(item.dstUrl);
item.dstBlob = item.file;
item.dstUrl = item.srcUrl;
item.dstW = item.srcW;
item.dstH = item.srcH;
item.kept = true;
item.encoding = false;
item.dstName = renderFilename(item, format);
renderCard(item);
return;
}
try {
const result = await workerEncode(item.file, opts);
if (item.dstUrl && item.dstUrl !== item.srcUrl) URL.revokeObjectURL(item.dstUrl);
item.dstBlob = result.blob;
item.dstUrl = URL.createObjectURL(result.blob);
item.dstW = result.w;
item.dstH = result.h;
item.kept = false;
item.dstName = renderFilename(item, format);
} catch (err) {
item.error = `Encode failed: ${err.message || err}`;
}
item.encoding = false;
renderCard(item);
}
let resizeTimer = null;
function scheduleResize() {
// Re-render in place so the single-card preview (aspect / fit / bg)
// tracks the controls without waiting for the debounced encode.
renderAllCards();
clearTimeout(resizeTimer);
resizeTimer = setTimeout(() => resizeAll(), 220);
}
async function resizeAll() {
if (items.length === 0) return;
statusEl.textContent = `Resizing ${items.length} image${items.length === 1 ? '' : 's'}β¦`;
syncFormatPills();
// Run sequentially through the worker (serial queue keeps memory bounded).
for (const it of items) {
if (!it.srcW) continue;
await encodeOne(it);
updateSummary();
}
statusEl.textContent = '';
}
// ββ Filename templating βββββββββββββββββββββββββββββββββββββββ
// Local lookup β `FORMAT_INFO` in image-utils.js is `const`, which classic
// scripts share but module scripts can't reach by bare name. The shape
// matches FORMAT_INFO (mime + ext).
const FORMAT_TABLE = {
png: { mime: 'image/png', ext: 'png' },
jpeg: { mime: 'image/jpeg', ext: 'jpg' },
webp: { mime: 'image/webp', ext: 'webp' },
};
const FORMAT_MIME = { png: 'image/png', jpeg: 'image/jpeg', webp: 'image/webp' };
function renderFilename(item, format) {
const ext = FORMAT_TABLE[format].ext;
const dot = item.name.lastIndexOf('.');
const stem = dot >= 0 ? item.name.slice(0, dot) : item.name;
const scalePct = item.srcW ? Math.round((item.dstW / item.srcW) * 100) : 100;
return settings.pattern
.replace('{name}', stem)
.replace('{w}', String(item.dstW || item.srcW))
.replace('{h}', String(item.dstH || item.srcH))
.replace('{scale}', `${scalePct}pct`)
.replace('{ext}', ext);
}
// ββ Rendering βββββββββββββββββββββββββββββββββββββββββββββββββ
function ensureCardEl(item) {
const wantClass = items.length === 1 ? 'single-card' : 'row-card';
let card = document.getElementById(`row-${item.id}`);
if (card) {
// Switching between single and bulk layout β swap the class so the
// CSS shape matches the new template.
if (card.className !== wantClass) card.className = wantClass;
return card;
}
card = document.createElement('div');
card.id = `row-${item.id}`;
card.className = wantClass;
filesEl.appendChild(card);
return card;
}
// The resize op preserves aspect when:
// - Percent mode (uniform scale)
// - Max mode + keep aspect (default)
// - Exact mode where the target W:H happens to match the source's
function isAspectPreserved(item) {
if (settings.mode === 'percent') return true;
if (settings.mode === 'max' && settings.max.keepAspect) return true;
if (settings.mode === 'exact' && item.srcW && item.srcH
&& settings.exact.targetW && settings.exact.targetH) {
const src = item.srcW / item.srcH;
const tgt = settings.exact.targetW / settings.exact.targetH;
return Math.abs((src - tgt) / src) < 0.01;
}
return false;
}
// Inline style for the single-card hero preview β adopts the active
// target aspect ratio (and matching object-fit + bg for exact mode).
function heroPreviewStyle(item) {
if (settings.mode === 'exact'
&& settings.exact.targetW && settings.exact.targetH) {
return `aspect-ratio:${settings.exact.targetW}/${settings.exact.targetH};object-fit:cover`;
}
if (item.srcW && item.srcH) {
return `aspect-ratio:${item.srcW}/${item.srcH};object-fit:cover`;
}
return '';
}
function deltaClass(after, before) {
if (!before) return 'delta-neutral';
const pct = (after - before) / before;
if (pct <= -0.02) return 'delta-good';
if (pct >= 0.02) return 'delta-bad';
return 'delta-neutral';
}
// Shared bits used by both row + single templates.
function statsLines(item) {
const srcSize = item.srcSize;
const dstSize = item.dstBlob ? item.dstBlob.size : 0;
const before = `${item.srcW || '?'}Γ${item.srcH || '?'} Β· ${srcExt(item.srcMime)} Β· ${formatBytes(srcSize)}`;
const fmtLabel = item.dstBlob ? (item.kept ? srcExt(item.srcMime) : resolveFormatFor(item).toUpperCase()) : '';
const after = item.error
? `<span class="text-red-400">${escapeHtml(item.error)}</span>`
: item.dstBlob
? `${item.dstW}Γ${item.dstH} Β· ${fmtLabel} Β· ${formatBytes(dstSize)}${item.kept ? ' Β· <span class="text-amber-400">kept original</span>' : ''}`
: item.encoding
? '<span class="text-gray-500">encodingβ¦</span>'
: '<span class="text-gray-500">queuedβ¦</span>';
const pct = (item.dstBlob && srcSize) ? formatPct(dstSize, srcSize) : '';
const pctCls = deltaClass(dstSize, srcSize);
return { before, after, pct, pctCls };
}
function renderCard(item) {
if (items.length === 1) {
if (isAspectPreserved(item)) renderSingleDiffCard(item);
else renderSingleHeroCard(item);
} else {
renderRowCard(item);
}
}
function renderRowCard(item) {
const card = ensureCardEl(item);
const { before, after, pct, pctCls } = statsLines(item);
card.innerHTML = `
<img class="thumb" src="${item.srcUrl}" alt="" loading="lazy">
<div class="min-w-0">
<div class="text-sm font-medium text-white truncate" title="${escapeHtml(item.dstName || item.name)}">${escapeHtml(item.dstName || item.name)}</div>
<div class="row-stats stats text-gray-500">${before}</div>
<div class="row-stats stats text-gray-200">β ${after}${pct ? ` <span class="${pctCls}">(${pct})</span>` : ''}</div>
</div>
<div class="row-actions">
<button class="btn btn-sm btn-primary" data-action="download" data-id="${item.id}" ${item.dstBlob ? '' : 'disabled'}>β¬οΈ</button>
<button class="btn btn-sm btn-secondary" data-action="reencode" data-id="${item.id}">π</button>
<button class="btn btn-sm btn-danger" data-action="remove" data-id="${item.id}">ποΈ</button>
</div>
`;
}
// Single + aspect-changing β show one big preview of the cropped/letterboxed
// result using srcUrl + CSS (object-fit). The encoded blob is identical
// visually so we don't wait for it.
function renderSingleHeroCard(item) {
const card = ensureCardEl(item);
const { before, after, pct, pctCls } = statsLines(item);
const previewStyle = heroPreviewStyle(item);
card.innerHTML = `
<div class="flex items-baseline justify-between gap-2 mb-3 min-w-0">
<span class="text-sm font-medium text-white truncate" title="${escapeHtml(item.dstName || item.name)}">${escapeHtml(item.dstName || item.name)}</span>
</div>
<img class="preview-area" src="${item.srcUrl}" alt="" style="${previewStyle}">
<div class="single-stats stats">
<div class="text-gray-500">${before}</div>
<div class="text-gray-200">β ${after}${pct ? ` <span class="${pctCls}">(${pct})</span>` : ''}</div>
</div>
<div class="single-actions">
<button class="btn btn-primary" data-action="download" data-id="${item.id}" ${item.dstBlob ? '' : 'disabled'}>β¬οΈ Download</button>
<button class="btn btn-secondary" data-action="reencode" data-id="${item.id}">π Re-run</button>
<button class="btn btn-danger" data-action="remove" data-id="${item.id}">ποΈ Remove</button>
</div>
`;
}
// Single + aspect-preserved β show a drag-to-compare diff slider once
// the encode finishes. Before encode completes (or when there's no
// dstUrl yet), fall back to a single source preview.
function renderSingleDiffCard(item) {
const card = ensureCardEl(item);
// Preserve the user's slider position across re-renders so a settings
// change after dragging doesn't snap back to 50%.
const oldSlider = card.querySelector('.diff-slider');
const savedSplit = oldSlider ? oldSlider.value : '50';
const { before, after, pct, pctCls } = statsLines(item);
const aspect = (item.srcW && item.srcH) ? `aspect-ratio:${item.srcW}/${item.srcH};` : '';
const visual = (item.dstBlob && !item.error)
? `
<div class="diff-wrap preview-area" style="${aspect}--split:${savedSplit}%;" data-id="${item.id}">
<img class="after" src="${item.dstUrl}" alt="After">
<img class="before" src="${item.srcUrl}" alt="Before">
<div class="diff-handle"></div>
<span class="diff-tag before">before</span>
<span class="diff-tag after">after</span>
<input type="range" class="diff-slider" min="0" max="100" value="${savedSplit}" aria-label="Reveal slider">
</div>`
: `<img class="preview-area" src="${item.srcUrl}" alt="" style="${aspect}object-fit:contain">`;
card.innerHTML = `
<div class="flex items-baseline justify-between gap-2 mb-3 min-w-0">
<span class="text-sm font-medium text-white truncate" title="${escapeHtml(item.dstName || item.name)}">${escapeHtml(item.dstName || item.name)}</span>
</div>
${visual}
<div class="single-stats stats">
<div class="text-gray-500">${before}</div>
<div class="text-gray-200">β ${after}${pct ? ` <span class="${pctCls}">(${pct})</span>` : ''}</div>
</div>
<div class="single-actions">
<button class="btn btn-primary" data-action="download" data-id="${item.id}" ${item.dstBlob ? '' : 'disabled'}>β¬οΈ Download</button>
<button class="btn btn-secondary" data-action="reencode" data-id="${item.id}">π Re-run</button>
<button class="btn btn-danger" data-action="remove" data-id="${item.id}">ποΈ Remove</button>
</div>
`;
}
function renderAllCards() {
for (const item of items) {
// refresh dstName under new pattern
if (item.dstBlob) item.dstName = renderFilename(item, resolveFormatFor(item));
renderCard(item);
}
}
// Diff slider drag β single-aspect-preserved card uses .diff-wrap.
filesEl.addEventListener('input', e => {
if (e.target.classList?.contains('diff-slider')) {
const wrap = e.target.closest('.diff-wrap');
if (wrap) wrap.style.setProperty('--split', `${e.target.value}%`);
}
});
filesEl.addEventListener('click', e => {
const btn = e.target.closest('button[data-action]');
if (!btn) return;
const item = items.find(i => i.id === btn.dataset.id);
if (!item) return;
if (btn.dataset.action === 'remove') {
if (item.srcUrl) URL.revokeObjectURL(item.srcUrl);
if (item.dstUrl && item.dstUrl !== item.srcUrl) URL.revokeObjectURL(item.dstUrl);
items.splice(items.indexOf(item), 1);
document.getElementById(`row-${item.id}`)?.remove();
if (items.length === 0) showEmpty();
else renderAllCards(); // remaining card may need single-mode template now
updateSummary();
syncFormatPills();
} else if (btn.dataset.action === 'download') {
downloadOne(item);
} else if (btn.dataset.action === 'reencode') {
encodeOne(item).then(updateSummary);
}
});
function showEmpty() {
controlsEl.classList.add('hidden');
summaryBar.classList.add('hidden');
dropEmpty.classList.remove('hidden');
dropCompact.classList.add('hidden');
dropEl.classList.remove('compact', 'p-3');
dropEl.classList.add('p-8');
}
function updateSummary() {
const n = items.length;
// "all" only reads naturally with 2+ items.
resizeBtn.textContent = n === 1 ? 'π Resize' : 'π Resize all';
zipBtn.textContent = n === 1 ? 'π¦ Download as zip' : 'π¦ Download all (zip)';
if (n === 0) { summaryBar.classList.add('hidden'); summaryBar.textContent = ''; return; }
summaryBar.classList.remove('hidden');
const totalBefore = items.reduce((a, i) => a + (i.srcSize || 0), 0);
const totalAfter = items.reduce((a, i) => a + (i.dstBlob ? i.dstBlob.size : 0), 0);
const ready = items.filter(i => i.dstBlob).length;
const kept = items.filter(i => i.kept).length;
const failed = items.filter(i => i.error).length;
const cls = deltaClass(totalAfter, totalBefore);
const pct = totalBefore ? formatPct(totalAfter, totalBefore) : '';
const tail = [];
if (kept) tail.push(`${kept} kept original`);
if (failed) tail.push(`${failed} failed`);
const tailStr = tail.length ? ` Β· ${tail.join(' Β· ')}` : '';
summaryBar.innerHTML = `${n} image${n === 1 ? '' : 's'} Β· ${formatBytes(totalBefore)} β ${formatBytes(totalAfter)} <span class="${cls}">(${pct})</span> Β· ${ready}/${n} ready${tailStr}`;
zipBtn.disabled = ready < 1;
}
function clearAll() {
for (const item of items) {
if (item.srcUrl) URL.revokeObjectURL(item.srcUrl);
if (item.dstUrl && item.dstUrl !== item.srcUrl) URL.revokeObjectURL(item.dstUrl);
}
items.length = 0;
filesEl.innerHTML = '';
clearError();
statusEl.textContent = '';
showEmpty();
updateSummary();
}
// ββ Download ββββββββββββββββββββββββββββββββββββββββββββββββββ
function uniqueName(base, taken) {
if (!taken.has(base)) { taken.add(base); return base; }
const dot = base.lastIndexOf('.');
const stem = dot >= 0 ? base.slice(0, dot) : base;
const ext = dot >= 0 ? base.slice(dot) : '';
let n = 1;
while (taken.has(`${stem}-${n}${ext}`)) n++;
const out = `${stem}-${n}${ext}`;
taken.add(out);
return out;
}
function downloadOne(item) {
if (!item.dstBlob) return;
const a = document.createElement('a');
a.href = item.dstUrl;
a.download = item.dstName || item.name;
document.body.appendChild(a);
a.click();
a.remove();
}
async function downloadZip() {
const ready = items.filter(i => i.dstBlob);
if (ready.length === 0) return;
zipBtn.disabled = true;
statusEl.textContent = `Packaging ${ready.length} image${ready.length === 1 ? '' : 's'} into a zipβ¦`;
const taken = new Set();
const entries = ready.map(i => ({
name: uniqueName(i.dstName || i.name, taken),
blob: i.dstBlob,
}));