-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
4149 lines (3508 loc) · 165 KB
/
script.js
File metadata and controls
4149 lines (3508 loc) · 165 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
// iresized.com - Multi-Tool Image Processing Suite
// Security-focused, client-side only
(function() {
'use strict';
// ===========================================
// SHARED STATE
// ===========================================
let originalImage = null;
let originalWidth = 0;
let originalHeight = 0;
let aspectRatio = 1;
let originalFileName = '';
let originalFileSize = 0;
let currentTool = 'resize';
let currentPost = null; // null = list view, post id = article view
// ===========================================
// BLOG POSTS
// ===========================================
//
// Voice: The Fed-Up Builder
// - First person singular. "I built this" not "we launched this."
// - PG-13 sarcasm. Dry, blunt, clearly annoyed but professional.
// - State the problem plainly, then state what you did about it.
// - Short paragraphs. 2-3 sentences max.
// - Specific over vague. Name the exact broken thing.
// - No marketing speak. No "excited to announce", no "game-changing."
// - End posts with something practical — what the user gets, not a CTA.
//
// Posts ordered newest-first. First item = featured post.
// To add a post: add an object to the TOP of this array.
const BLOG_POSTS = [
{
id: 'clipboard-paste-copy',
title: 'Stop Saving Files You\'re Going to Delete Immediately',
date: '2026-03-10',
readTime: '1 min read',
excerpt: 'Paste a screenshot directly into any tool. Copy the result straight back to your clipboard. No temp files.',
body: [
"The workflow was: take a screenshot, save it somewhere, open the tab, click upload, find the file, process it, download the result, open it in whatever you actually needed. Every single time.",
"I built clipboard paste and copy into iResized because that entire chain is unnecessary. Your browser already has the image. There\u2019s no reason to touch the filesystem.",
"The paste button sits in the upload area on every tool. Hit it and your clipboard screenshot drops straight in. When the tool finishes, every output has a copy button that writes the result directly back to your clipboard.",
"It\u2019s built on navigator.clipboard.read() and navigator.clipboard.write() \u2014 zero dependencies, pure browser API. Works in any modern browser over HTTPS. Squoosh doesn\u2019t have this. Most online tools don\u2019t because they\u2019re designed around server-side processing and file uploads.",
"You get a screenshot-to-result pipeline that never touches your downloads folder."
]
},
{
id: 'batch-processing-zip-download',
title: 'I Got Tired of Downloading Images One at a Time',
date: '2026-03-10',
readTime: '2 min read',
excerpt: 'Bulk image processing exists everywhere \u2014 but only if you pay or accept arbitrary limits.',
body: [
"Every batch image tool on the internet has a catch. BeFunky charges $6.99/month. TinyPNG lets you process 20 images free per month, then stops. iLoveIMG quietly caps how many you can do at once. The free tier is always the bait.",
"The actual broken thing isn\u2019t the processing \u2014 it\u2019s the download step. You resize 20 images and then click \u2018Download\u2019 twenty separate times. That\u2019s not a workflow, that\u2019s punishment.",
"I built batch processing into iResized. Upload 10 to 50 images, pick an operation \u2014 resize, compress, or convert \u2014 and it runs through all of them at once. A progress bar shows exactly which file is being processed so you\u2019re not staring at a spinner wondering if it crashed.",
"When it\u2019s done, JSZip bundles everything into a single ZIP file. One click, all your files. No account, no monthly limit, no watermark.",
"Client-side processing means nothing leaves your machine. The ZIP gets built in your browser. That\u2019s the whole feature \u2014 bulk processing that doesn\u2019t treat free users as a revenue problem to solve."
]
},
{
id: 'auto-enhance-one-click-levels',
title: 'Auto-Enhance: One Click to Fix a Flat Photo',
date: '2026-03-10',
readTime: '2 min read',
excerpt: 'Fotor charges for it. Pixlr locks it behind Pro. I put it in for free because it\u2019s 40 lines of JavaScript.',
body: [
"The number one thing people want from an image tool is \u2018make it look better.\u2019 Most phone photos are slightly flat, slightly dark, or blown out. Not unusable \u2014 just dull.",
"Fotor charges for auto-enhance. Pixlr limits it to Pro users. Adobe Express gates its AI enhance behind a paid plan. The feature is not complicated enough to justify any of that.",
"I built it with pure Canvas 2D \u2014 getImageData, some histogram math, putImageData. About 40 lines of JavaScript. No library. It computes per-channel histograms, then stretches the 5th-to-95th percentile range to fill 0\u2013255. That\u2019s it. That\u2019s the whole algorithm.",
"There\u2019s a strength slider so you can blend between the original and the enhanced version at 0\u2013100%. Useful when the auto result is slightly too punchy.",
"After applying, it shows you the actual numbers: brightness delta, contrast delta, per-channel ranges before and after. You can see exactly what changed and by how much. One click, no subscription."
]
},
{
id: 'resize-to-target-file-size',
title: 'Stop Guessing. Enter a Size, Get That Size.',
date: '2026-03-10',
readTime: '2 min read',
excerpt: 'Email attachment limits and CMS upload caps shouldn\u2019t require 20 minutes of manual compress-and-pray.',
body: [
"Every few days someone hits a 1MB email attachment limit, or a form that caps uploads at 500KB. Their solution: compress the image, check the file size, compress again, check again. Repeat until close enough or completely defeated.",
"No free tool solves this cleanly. ImageResizer.com will solve it for $10/month. Everyone else either ignores the problem or makes you do the math yourself.",
"I built a target file size input into iresized. You type in a number \u2014 KB or MB \u2014 and the tool finds the right JPEG quality automatically. No slider-dragging. No guessing.",
"Under the hood it\u2019s a binary search on the canvas.toBlob() quality parameter. Converges in about 8 iterations, takes roughly 200ms. Zero dependencies, pure JavaScript running entirely in your browser.",
"You get an image at or under your target size. That\u2019s it. No account, no paywall, no watermark on something you already owned."
]
},
{
id: 'avif-webp-format-conversion',
title: 'AVIF and WebP Conversion Without the Paywall',
date: '2026-03-10',
readTime: '2 min read',
excerpt: 'AVIF files are 40% smaller than JPEG and somehow every converter wants a subscription to produce one.',
body: [
"AVIF and WebP have been the right answer for web images for years. AVIF cuts file sizes 30\u201350% versus JPEG at equivalent quality. The browser has supported it since Chrome 85, which covers 95%+ of your users. There\u2019s no good reason not to use it.",
"And yet here we are. iLoveIMG charges for AVIF conversion. Most server-side tools have daily limits. Squoosh is free but processes one image at a time, which is fine until you have forty product shots to convert.",
"The annoying part is that the encoder is already sitting in your browser. canvas.toBlob() handles AVIF, WebP, JPEG, and PNG natively. No server needed. No account. No metered API call going to someone\u2019s infrastructure.",
"So I wired it up properly. Drop your images, pick your output format, set the quality slider, download. Bulk conversion works the same way as single \u2014 you\u2019re just doing more of them.",
"You get client-side conversion to all four formats, a quality slider so you\u2019re not guessing, and no file leaving your machine. That\u2019s the whole thing."
]
},
{
id: 'watermark-removal-done-properly',
title: 'Watermark Removal, Done Properly',
date: '2026-03-10',
readTime: '2 min read',
excerpt: 'Gemini puts a 4-pointed star on every image it generates. Most tools want $10/month to badly clone-stamp it out.',
body: [
"Gemini puts a semi-transparent 4-pointed star watermark on every image it generates. Bottom-right corner. 48 pixels on small images, 96 on large ones, plus a 32-pixel margin from the edge.",
"Most \"watermark removers\" online want $10/month to clone-stamp it. Our first attempt wasn't much better. The original algorithm copied pixels from a full patch-width away \u2014 grabbing completely unrelated content \u2014 then blended them with the watermarked pixels at the edges. The star was still there, just blurry.",
"So I rewrote it. The new approach is called edge-propagation inpainting. Instead of copying from far away, it samples a thin strip of clean pixels from immediately above and to the left of the watermark area. It builds color profiles from those strips, then fills inward using inverse-distance interpolation.",
"Pixels near the top edge get mostly the top strip\u2019s colors. Pixels near the left edge get mostly the left strip\u2019s colors. Pixels in the deep corner get a blend of both plus the corner sample. Then it adds a tiny amount of Gaussian noise calibrated to the texture of the surrounding area, so the result doesn\u2019t look artificially smooth.",
"No blending with the original watermarked pixels. Every pixel in the patch is fully replaced. The patch auto-sizes to 96px for images up to 1024px, or 144px for larger images.",
"Upload a Gemini image. The watermark is gone. You keep the full resolution. It takes about 50 milliseconds."
]
},
{
id: 'why-we-built-this',
title: 'Why We Built This',
date: '2026-03-10',
readTime: '3 min read',
excerpt: "Every image tool on the internet follows the same playbook. Free tier with a watermark. \"Premium\" for $12/month.",
body: [
"Every image tool on the internet follows the same playbook. Free tier that watermarks your output or limits you to three images a day. \"Premium\" tier for $12/month. Enterprise pricing if you ask nicely.",
"Resizing a JPEG is not a premium feature. It\u2019s a canvas element and two lines of JavaScript. Stripping EXIF data is reading bytes and writing fewer bytes. Compressing an image is literally what the browser\u2019s built-in encoder already does.",
"These aren\u2019t hard problems. They were solved decades ago. The tools that charge for them aren\u2019t selling technology \u2014 they\u2019re selling convenience with a padlock on it.",
"I built iresized.com because I got tired of it. Every tool here runs entirely in your browser. Your images never leave your machine. There\u2019s no server, no account, no upload queue, no daily limit. The code is open source.",
"There\u2019s no catch. No freemium upsell. No \"pro\" tier coming next quarter. The tools work, they\u2019re free, and they\u2019ll stay that way.",
"If a resize tool can be built in 45 seconds by an AI coding assistant, it has no business costing $12 a month. That\u2019s the whole thesis."
]
}
];
// Crop-specific state
let cropSelection = { x: 0, y: 0, width: 0, height: 0 };
let cropAspectRatio = null; // null = free
let isDragging = false;
let dragStart = { x: 0, y: 0 };
let canvasScale = 1;
// ===========================================
// DOM ELEMENTS
// ===========================================
const elements = {
// Tabs
tabButtons: document.querySelectorAll('.tab-btn'),
toolPanels: document.querySelectorAll('.tool-panel'),
// Shared
dropZone: document.getElementById('drop-zone'),
fileInput: document.getElementById('file-input'),
previewArea: document.getElementById('preview-area'),
mainDivider: document.getElementById('main-divider'),
imagePreview: document.getElementById('image-preview'),
removeBtn: document.getElementById('remove-btn'),
originalDims: document.getElementById('original-dims'),
fileName: document.getElementById('file-name'),
// Resize
widthInput: document.getElementById('width'),
heightInput: document.getElementById('height'),
lockBtn: document.getElementById('lock-btn'),
qualitySlider: document.getElementById('quality-slider'),
qualityVal: document.getElementById('quality-val'),
formatSelect: document.getElementById('format-select'),
resizeFilename: document.getElementById('resize-filename'),
resizeFilenameExt: document.getElementById('resize-filename-ext'),
resizeBtn: document.getElementById('resize-btn'),
// Compress
compressQualitySlider: document.getElementById('compress-quality-slider'),
compressQualityVal: document.getElementById('compress-quality-val'),
compressFormatSelect: document.getElementById('compress-format-select'),
compressFilename: document.getElementById('compress-filename'),
compressFilenameExt: document.getElementById('compress-filename-ext'),
compressBtn: document.getElementById('compress-btn'),
// Crop
cropCanvasContainer: document.getElementById('crop-canvas-container'),
cropCanvas: document.getElementById('crop-canvas'),
cropRemoveBtn: document.getElementById('crop-remove-btn'),
cropDims: document.getElementById('crop-dims'),
cropFileName: document.getElementById('crop-file-name'),
aspectButtons: document.querySelectorAll('.aspect-btn'),
cropSelectionDims: document.getElementById('crop-selection-dims'),
cropFormatSelect: document.getElementById('crop-format-select'),
cropFilename: document.getElementById('crop-filename'),
cropFilenameExt: document.getElementById('crop-filename-ext'),
cropBtn: document.getElementById('crop-btn'),
// Metadata
metadataFormatSelect: document.getElementById('metadata-format-select'),
metadataFilename: document.getElementById('metadata-filename'),
metadataFilenameExt: document.getElementById('metadata-filename-ext'),
metadataBtn: document.getElementById('metadata-btn'),
// HEIC Converter
heicDropZone: document.getElementById('heic-drop-zone'),
heicFileInput: document.getElementById('heic-file-input'),
heicFileListContainer: document.getElementById('heic-file-list-container'),
heicFileList: document.getElementById('heic-file-list'),
heicClearBtn: document.getElementById('heic-clear-btn'),
heicFormatSelect: document.getElementById('heic-format-select'),
heicQualitySlider: document.getElementById('heic-quality-slider'),
heicQualityVal: document.getElementById('heic-quality-val'),
heicConvertBtn: document.getElementById('heic-convert-btn'),
// Bulk Rename
bulkDropZone: document.getElementById('bulk-drop-zone'),
bulkFileInput: document.getElementById('bulk-file-input'),
bulkFileListContainer: document.getElementById('bulk-file-list-container'),
bulkFileList: document.getElementById('bulk-file-list'),
bulkFileCount: document.getElementById('bulk-file-count'),
bulkClearBtn: document.getElementById('bulk-clear-btn'),
bulkPattern: document.getElementById('bulk-pattern'),
bulkStartNum: document.getElementById('bulk-start-num'),
bulkZipFilename: document.getElementById('bulk-zip-filename'),
bulkRenameBtn: document.getElementById('bulk-rename-btn'),
// Background Remover
bgDropZone: document.getElementById('bg-drop-zone'),
bgFileInput: document.getElementById('bg-file-input'),
bgPreviewContainer: document.getElementById('bg-preview-container'),
bgPreviewCanvas: document.getElementById('bg-preview-canvas'),
bgLoading: document.getElementById('bg-loading'),
bgClearBtn: document.getElementById('bg-clear-btn'),
bgFormatSelect: document.getElementById('bg-format-select'),
bgFilename: document.getElementById('bg-filename'),
bgFilenameExt: document.getElementById('bg-filename-ext'),
bgDownloadBtn: document.getElementById('bg-download-btn'),
// Advanced Background Remover
advbgDropZone: document.getElementById('advbg-drop-zone'),
advbgFileInput: document.getElementById('advbg-file-input'),
advbgPreviewContainer: document.getElementById('advbg-preview-container'),
advbgPreviewCanvas: document.getElementById('advbg-preview-canvas'),
advbgLoading: document.getElementById('advbg-loading'),
advbgLoadingText: document.getElementById('advbg-loading-text'),
advbgProgress: document.getElementById('advbg-progress'),
advbgProgressFill: document.getElementById('advbg-progress-fill'),
advbgProgressText: document.getElementById('advbg-progress-text'),
advbgClearBtn: document.getElementById('advbg-clear-btn'),
advbgFormatSelect: document.getElementById('advbg-format-select'),
advbgFilename: document.getElementById('advbg-filename'),
advbgFilenameExt: document.getElementById('advbg-filename-ext'),
advbgDownloadBtn: document.getElementById('advbg-download-btn'),
advbgInfoBox: document.getElementById('advbg-info-box'),
// Watermark Removal
watermarkPatchSlider: document.getElementById('watermark-patch-slider'),
watermarkPatchVal: document.getElementById('watermark-patch-val'),
watermarkQualitySlider: document.getElementById('watermark-quality-slider'),
watermarkQualityVal: document.getElementById('watermark-quality-val'),
watermarkFormatSelect: document.getElementById('watermark-format-select'),
watermarkFilename: document.getElementById('watermark-filename'),
watermarkFilenameExt: document.getElementById('watermark-filename-ext'),
watermarkBtn: document.getElementById('watermark-btn'),
watermarkCopyBtn: document.getElementById('watermark-copy-btn'),
// Clipboard
pasteBtn: document.getElementById('paste-btn'),
resizeCopyBtn: document.getElementById('resize-copy-btn'),
compressCopyBtn: document.getElementById('compress-copy-btn'),
cropCopyBtn: document.getElementById('crop-copy-btn'),
metadataCopyBtn: document.getElementById('metadata-copy-btn'),
// Adjust (Colour Correction)
adjustBrightness: document.getElementById('adjust-brightness'),
adjustBrightnessVal: document.getElementById('adjust-brightness-val'),
adjustContrast: document.getElementById('adjust-contrast'),
adjustContrastVal: document.getElementById('adjust-contrast-val'),
adjustSaturation: document.getElementById('adjust-saturation'),
adjustSaturationVal: document.getElementById('adjust-saturation-val'),
adjustHue: document.getElementById('adjust-hue'),
adjustHueVal: document.getElementById('adjust-hue-val'),
adjustQualitySlider: document.getElementById('adjust-quality-slider'),
adjustQualityVal: document.getElementById('adjust-quality-val'),
adjustFormatSelect: document.getElementById('adjust-format-select'),
adjustFilename: document.getElementById('adjust-filename'),
adjustFilenameExt: document.getElementById('adjust-filename-ext'),
adjustResetBtn: document.getElementById('adjust-reset-btn'),
adjustBtn: document.getElementById('adjust-btn'),
// Filters (Preset Effects)
filtersGrid: document.getElementById('filters-grid'),
filtersQualitySlider: document.getElementById('filters-quality-slider'),
filtersQualityVal: document.getElementById('filters-quality-val'),
filtersFormatSelect: document.getElementById('filters-format-select'),
filtersFilename: document.getElementById('filters-filename'),
filtersFilenameExt: document.getElementById('filters-filename-ext'),
filtersBtn: document.getElementById('filters-btn'),
// Add Watermark
addwmText: document.getElementById('addwm-text'),
addwmSizeSlider: document.getElementById('addwm-size-slider'),
addwmSizeVal: document.getElementById('addwm-size-val'),
addwmOpacitySlider: document.getElementById('addwm-opacity-slider'),
addwmOpacityVal: document.getElementById('addwm-opacity-val'),
addwmRotationSlider: document.getElementById('addwm-rotation-slider'),
addwmRotationVal: document.getElementById('addwm-rotation-val'),
addwmColour: document.getElementById('addwm-colour'),
addwmPosition: document.getElementById('addwm-position'),
addwmFormatSelect: document.getElementById('addwm-format-select'),
addwmQualitySlider: document.getElementById('addwm-quality-slider'),
addwmQualityVal: document.getElementById('addwm-quality-val'),
addwmFilename: document.getElementById('addwm-filename'),
addwmFilenameExt: document.getElementById('addwm-filename-ext'),
addwmBtn: document.getElementById('addwm-btn'),
// Auto-Enhance
enhanceRunBtn: document.getElementById('enhance-run-btn'),
enhanceResults: document.getElementById('enhance-results'),
enhanceStats: document.getElementById('enhance-stats'),
enhanceStrengthGroup: document.getElementById('enhance-strength-group'),
enhanceStrengthSlider: document.getElementById('enhance-strength-slider'),
enhanceStrengthVal: document.getElementById('enhance-strength-val'),
enhanceQualitySlider: document.getElementById('enhance-quality-slider'),
enhanceQualityVal: document.getElementById('enhance-quality-val'),
enhanceFormatSelect: document.getElementById('enhance-format-select'),
enhanceFilename: document.getElementById('enhance-filename'),
enhanceFilenameExt: document.getElementById('enhance-filename-ext'),
enhanceDownloadBtn: document.getElementById('enhance-download-btn')
};
// ===========================================
// SECURITY UTILITIES
// ===========================================
/**
* Validate positive integer within bounds
* Security: Prevents NaN, Infinity, negative, and overflow attacks
*/
function validatePositiveInt(value, min = 1, max = 10000) {
const num = parseInt(value, 10);
if (!Number.isFinite(num) || num < min || num > max) {
return null;
}
return num;
}
/**
* Sanitize filename - prevents path traversal and injection
* Security: Blocks ../, ..\, <, >, etc.
*/
function sanitizeFilename(name) {
if (typeof name !== 'string') return 'image';
return name
// Remove path traversal attempts
.replace(/\.\./g, '')
.replace(/[/\\]/g, '')
// Remove dangerous characters
.replace(/[<>:"|?*\x00-\x1f]/g, '-')
// Normalize spaces and dashes
.replace(/\s+/g, '-')
.replace(/-+/g, '-')
// Remove leading dots (hidden files)
.replace(/^\.+/, '')
// Limit length
.substring(0, 200)
.trim() || 'image';
}
/**
* Format file size for display
* Security: Uses textContent, safe from XSS
*/
function formatFileSize(bytes) {
if (typeof bytes !== 'number' || bytes < 0) return '0 B';
if (bytes < 1024) return bytes + ' B';
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
}
/**
* Download blob with sanitized filename
*/
function downloadBlob(blob, filename) {
if (!blob) {
alert('Error processing image. Please try again.');
return;
}
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = sanitizeFilename(filename);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
// Clean up memory
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
/**
* Clean up canvas memory
* Security: Prevents memory exhaustion attacks
*/
function cleanupCanvas(canvas) {
if (canvas) {
canvas.width = 0;
canvas.height = 0;
}
}
/**
* Safe tool execution wrapper
* Security: Isolates errors per tool
*/
function safeExecute(fn, toolName) {
try {
const result = fn();
if (result && typeof result.catch === 'function') {
result.catch(function(err) {
console.error(`${toolName} error:`, err);
alert(`${toolName} encountered an error. Please try again.`);
});
}
} catch (err) {
console.error(`${toolName} error:`, err);
alert(`${toolName} encountered an error. Please try again.`);
}
}
// ===========================================
// FILENAME HELPERS
// ===========================================
/**
* Update all filename inputs with default values based on tool
*/
function updateFilenameDefaults() {
const baseName = originalFileName || 'image';
elements.resizeFilename.value = `${baseName}_resized`;
elements.compressFilename.value = `${baseName}_compressed`;
elements.cropFilename.value = `${baseName}_cropped`;
elements.metadataFilename.value = `${baseName}_clean`;
elements.watermarkFilename.value = `${baseName}_nowm`;
elements.adjustFilename.value = `${baseName}_adjusted`;
elements.filtersFilename.value = `${baseName}_filtered`;
if (elements.fcFilename) elements.fcFilename.value = `${baseName}_converted`;
if (elements.tsFilename) elements.tsFilename.value = `${baseName}_optimized`;
elements.addwmFilename.value = `${baseName}_watermarked`;
elements.enhanceFilename.value = `${baseName}_enhanced`;
}
/**
* Update extension display for a given format select and extension element
*/
function updateExtensionDisplay(formatSelect, extElement) {
const format = formatSelect.value;
extElement.textContent = `.${format}`;
}
/**
* Get filename for download - uses custom name or falls back to default
*/
function getDownloadFilename(filenameInput, defaultSuffix, format) {
const customName = filenameInput.value.trim();
const baseName = customName || `${originalFileName || 'image'}${defaultSuffix}`;
return `${sanitizeFilename(baseName)}.${format}`;
}
// ===========================================
// TAB NAVIGATION
// ===========================================
function initTabs() {
elements.tabButtons.forEach(tab => {
tab.addEventListener('click', () => {
const tool = tab.dataset.tool;
switchTool(tool);
});
});
}
function switchTool(tool) {
currentTool = tool;
// Update tab states
elements.tabButtons.forEach(t => {
const isActive = t.dataset.tool === tool;
t.classList.toggle('active', isActive);
t.setAttribute('aria-selected', isActive ? 'true' : 'false');
});
// Update panel visibility
elements.toolPanels.forEach(p => {
p.classList.toggle('active', p.id === `${tool}-panel`);
});
// Apply or clear adjust preview filter on the shared preview image
if (tool === 'adjust') {
applyAdjustPreview();
} else {
clearAdjustPreview();
}
// Rebuild filter thumbnails when switching to filters tab
if (tool === 'filters') {
buildFilterThumbnails();
}
// Trigger size estimate when switching to format-convert with an image loaded
if (tool === 'format-convert' && originalImage) {
scheduleFcEstimate();
}
// Tools with their own upload zones (HEIC, Bulk, Background, Advanced BG, PDF, Batch)
const hasOwnUploadZone = (tool === 'convert' || tool === 'bulk' || tool === 'background' || tool === 'advancedbg' || tool === 'topdf' || tool === 'batch');
if (hasOwnUploadZone) {
// Hide shared upload zone and divider for multi-file tools
elements.dropZone.classList.add('hidden');
elements.previewArea.classList.add('hidden');
elements.cropCanvasContainer.classList.add('hidden');
elements.mainDivider.classList.add('hidden');
} else if (tool === 'crop' && originalImage) {
// Crop tool uses canvas
elements.dropZone.classList.add('hidden');
elements.previewArea.classList.add('hidden');
elements.cropCanvasContainer.classList.remove('hidden');
elements.mainDivider.classList.remove('hidden');
initCropCanvas();
} else if (originalImage) {
// Other single-image tools show preview
elements.dropZone.classList.add('hidden');
elements.cropCanvasContainer.classList.add('hidden');
elements.previewArea.classList.remove('hidden');
elements.mainDivider.classList.remove('hidden');
} else {
// No image loaded - show shared upload zone
elements.dropZone.classList.remove('hidden');
elements.previewArea.classList.add('hidden');
elements.cropCanvasContainer.classList.add('hidden');
elements.mainDivider.classList.remove('hidden');
}
}
// ===========================================
// SHARED UPLOAD FUNCTIONALITY
// ===========================================
function initUpload() {
const { dropZone, fileInput, removeBtn, cropRemoveBtn } = elements;
dropZone.addEventListener('click', () => fileInput.click());
dropZone.addEventListener('dragover', handleDragOver);
dropZone.addEventListener('dragleave', handleDragLeave);
dropZone.addEventListener('drop', handleDrop);
fileInput.addEventListener('change', handleFileSelect);
removeBtn.addEventListener('click', (e) => {
e.stopPropagation();
resetState();
});
cropRemoveBtn.addEventListener('click', (e) => {
e.stopPropagation();
resetState();
});
}
function handleDragOver(e) {
e.preventDefault();
e.stopPropagation();
elements.dropZone.classList.add('drag-over');
}
function handleDragLeave(e) {
e.preventDefault();
e.stopPropagation();
elements.dropZone.classList.remove('drag-over');
}
function handleDrop(e) {
e.preventDefault();
e.stopPropagation();
elements.dropZone.classList.remove('drag-over');
const files = e.dataTransfer.files;
if (files.length > 0) {
handleFile(files[0]);
}
}
function handleFileSelect(e) {
const files = e.target.files;
if (files.length > 0) {
handleFile(files[0]);
}
}
function handleFile(file) {
// Security: Validate file type
if (!file.type.startsWith('image/')) {
alert('Please select a valid image file.');
return;
}
// Security: Check file size (max 100MB)
if (file.size > 100 * 1024 * 1024) {
alert('File too large. Maximum size is 100MB.');
return;
}
originalFileName = file.name.replace(/\.[^/.]+$/, '');
originalFileSize = file.size;
const reader = new FileReader();
reader.onload = function(e) {
const img = new Image();
img.onload = function() {
originalImage = img;
originalWidth = img.naturalWidth;
originalHeight = img.naturalHeight;
aspectRatio = originalWidth / originalHeight;
showPreview(e.target.result, file);
};
img.onerror = function() {
alert('Error loading image. The file may be corrupted.');
};
img.src = e.target.result;
};
reader.onerror = function() {
alert('Error reading file. Please try again.');
};
reader.readAsDataURL(file);
}
function showPreview(dataUrl, file) {
const { imagePreview, originalDims, fileName, dropZone, previewArea,
cropCanvasContainer, cropDims, cropFileName, widthInput, heightInput } = elements;
// Update standard preview
imagePreview.src = dataUrl;
originalDims.textContent = `${originalWidth} × ${originalHeight}px`;
fileName.textContent = formatFileSize(file.size) + ' | ' + file.name;
// Update crop preview info
cropDims.textContent = `${originalWidth} × ${originalHeight}px`;
cropFileName.textContent = formatFileSize(file.size) + ' | ' + file.name;
// Set resize dimension inputs
widthInput.value = originalWidth;
heightInput.value = originalHeight;
// Auto-size watermark patch slider based on image dimensions
if (originalWidth > 0 && originalHeight > 0) {
var recommended = computePatchSize(originalWidth, originalHeight);
elements.watermarkPatchSlider.value = recommended;
elements.watermarkPatchVal.textContent = recommended + 'px';
}
// Set default filenames for all tools
updateFilenameDefaults();
// Show appropriate preview based on current tool
dropZone.classList.add('hidden');
if (currentTool === 'crop') {
previewArea.classList.add('hidden');
cropCanvasContainer.classList.remove('hidden');
initCropCanvas();
} else {
cropCanvasContainer.classList.add('hidden');
previewArea.classList.remove('hidden');
}
// Apply adjust filter if that tool is active, otherwise clear
if (currentTool === 'adjust') {
applyAdjustPreview();
} else {
clearAdjustPreview();
}
// Rebuild filter thumbnails if filters tab is active
if (currentTool === 'filters') {
buildFilterThumbnails();
}
// Update format-convert size estimate if that tool is active
if (currentTool === 'format-convert') {
scheduleFcEstimate();
}
}
function resetState() {
originalImage = null;
originalWidth = 0;
originalHeight = 0;
aspectRatio = 1;
originalFileName = '';
originalFileSize = 0;
// Reset crop state
cropSelection = { x: 0, y: 0, width: 0, height: 0 };
// Reset inputs
elements.widthInput.value = '';
elements.heightInput.value = '';
elements.fileInput.value = '';
elements.cropSelectionDims.textContent = 'Select area on image';
// Reset UI
elements.previewArea.classList.add('hidden');
elements.cropCanvasContainer.classList.add('hidden');
elements.dropZone.classList.remove('hidden');
// Clean up canvas memory
cleanupCanvas(elements.cropCanvas);
// Clear adjust preview filter and rebuild filters grid to empty state
clearAdjustPreview();
selectedFilterIndex = 0;
buildFilterThumbnails();
// Reset enhance state
enhanceOriginalData = null;
enhanceEnhancedData = null;
enhanceWidth = 0;
enhanceHeight = 0;
elements.enhanceResults.classList.add('hidden');
elements.enhanceStrengthGroup.classList.add('hidden');
elements.enhanceDownloadBtn.disabled = true;
elements.enhanceStrengthSlider.value = 100;
elements.enhanceStrengthVal.textContent = '100%';
// Reset target-size state
tsResultBlob = null;
elements.tsResult.classList.add('hidden');
elements.tsDownloadBtn.disabled = true;
}
// ===========================================
// RESIZE TOOL
// ===========================================
let isAspectLocked = true;
function initResizeTool() {
const { widthInput, heightInput, lockBtn, qualitySlider, qualityVal,
formatSelect, resizeFilenameExt, resizeBtn } = elements;
widthInput.addEventListener('input', handleWidthChange);
heightInput.addEventListener('input', handleHeightChange);
lockBtn.addEventListener('click', toggleAspectLock);
qualitySlider.addEventListener('input', () => {
qualityVal.textContent = qualitySlider.value + '%';
});
formatSelect.addEventListener('change', () => {
updateQualityVisibility(formatSelect, qualitySlider);
updateExtensionDisplay(formatSelect, resizeFilenameExt);
});
resizeBtn.addEventListener('click', () => safeExecute(processResize, 'Resize'));
updateQualityVisibility(formatSelect, qualitySlider);
updateExtensionDisplay(formatSelect, resizeFilenameExt);
}
function handleWidthChange() {
const newWidth = validatePositiveInt(elements.widthInput.value, 1, 20000);
if (isAspectLocked && newWidth && aspectRatio) {
const newHeight = Math.round(newWidth / aspectRatio);
elements.heightInput.value = newHeight;
}
}
function handleHeightChange() {
const newHeight = validatePositiveInt(elements.heightInput.value, 1, 20000);
if (isAspectLocked && newHeight && aspectRatio) {
const newWidth = Math.round(newHeight * aspectRatio);
elements.widthInput.value = newWidth;
}
}
function toggleAspectLock() {
isAspectLocked = !isAspectLocked;
elements.lockBtn.classList.toggle('active', isAspectLocked);
elements.lockBtn.title = isAspectLocked ? 'Unlock Aspect Ratio' : 'Lock Aspect Ratio';
}
function updateQualityVisibility(formatSelect, qualitySlider) {
const format = formatSelect.value;
const qualityGroup = qualitySlider.closest('.control-group');
if (format === 'png') {
qualityGroup.style.opacity = '0.5';
qualityGroup.style.pointerEvents = 'none';
} else {
qualityGroup.style.opacity = '1';
qualityGroup.style.pointerEvents = 'auto';
}
}
function processResize() {
if (!originalImage) {
alert('Please upload an image first.');
return;
}
const targetWidth = validatePositiveInt(elements.widthInput.value, 1, 20000) || originalWidth;
const targetHeight = validatePositiveInt(elements.heightInput.value, 1, 20000) || originalHeight;
if (!targetWidth || !targetHeight) {
alert('Please enter valid dimensions (1-20000 pixels).');
return;
}
if (targetWidth > 10000 || targetHeight > 10000) {
if (!confirm('Large dimensions may cause performance issues. Continue?')) {
return;
}
}
const format = elements.formatSelect.value;
const quality = parseInt(elements.qualitySlider.value, 10) / 100;
const canvas = document.createElement('canvas');
canvas.width = targetWidth;
canvas.height = targetHeight;
const ctx = canvas.getContext('2d');
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = 'high';
ctx.drawImage(originalImage, 0, 0, targetWidth, targetHeight);
const mimeType = `image/${format === 'jpg' ? 'jpeg' : format}`;
const filename = getDownloadFilename(elements.resizeFilename, '_resized', format);
canvas.toBlob(function(blob) {
downloadBlob(blob, filename);
cleanupCanvas(canvas);
}, mimeType, format === 'png' ? undefined : quality);
}
// ===========================================
// COMPRESS TOOL
// ===========================================
function initCompressTool() {
const { compressQualitySlider, compressQualityVal, compressFormatSelect,
compressFilenameExt, compressBtn } = elements;
compressQualitySlider.addEventListener('input', () => {
compressQualityVal.textContent = compressQualitySlider.value + '%';
});
compressFormatSelect.addEventListener('change', () => {
updateQualityVisibility(compressFormatSelect, compressQualitySlider);
updateExtensionDisplay(compressFormatSelect, compressFilenameExt);
});
compressBtn.addEventListener('click', () => safeExecute(processCompress, 'Compress'));
updateQualityVisibility(compressFormatSelect, compressQualitySlider);
updateExtensionDisplay(compressFormatSelect, compressFilenameExt);
}
function processCompress() {
if (!originalImage) {
alert('Please upload an image first.');
return;
}
const format = elements.compressFormatSelect.value;
const quality = parseInt(elements.compressQualitySlider.value, 10) / 100;
const canvas = document.createElement('canvas');
canvas.width = originalWidth;
canvas.height = originalHeight;
const ctx = canvas.getContext('2d');
ctx.drawImage(originalImage, 0, 0);
const mimeType = `image/${format === 'jpg' ? 'jpeg' : format}`;
const filename = getDownloadFilename(elements.compressFilename, '_compressed', format);
canvas.toBlob(function(blob) {
downloadBlob(blob, filename);
cleanupCanvas(canvas);
}, mimeType, format === 'png' ? undefined : quality);
}
// ===========================================
// STRIP EXIF/METADATA TOOL
// ===========================================
function initMetadataTool() {
const { metadataFormatSelect, metadataFilenameExt, metadataBtn } = elements;
metadataFormatSelect.addEventListener('change', () => {
updateExtensionDisplay(metadataFormatSelect, metadataFilenameExt);
});
metadataBtn.addEventListener('click', () => safeExecute(processStripMetadata, 'Strip Metadata'));
updateExtensionDisplay(metadataFormatSelect, metadataFilenameExt);
}
function processStripMetadata() {
if (!originalImage) {
alert('Please upload an image first.');
return;
}
const format = elements.metadataFormatSelect.value;
// Canvas naturally strips all EXIF/metadata when re-encoding
const canvas = document.createElement('canvas');
canvas.width = originalWidth;
canvas.height = originalHeight;
const ctx = canvas.getContext('2d');
ctx.drawImage(originalImage, 0, 0);
const mimeType = `image/${format === 'jpg' ? 'jpeg' : format}`;
// Use high quality since we're not trying to compress
const quality = 0.95;
const filename = getDownloadFilename(elements.metadataFilename, '_clean', format);
canvas.toBlob(function(blob) {
downloadBlob(blob, filename);
cleanupCanvas(canvas);
}, mimeType, format === 'png' ? undefined : quality);
}
// ===========================================
// CROP TOOL (Enhanced with move/resize handles)
// ===========================================
// Drag modes
const DRAG_MODE = {
NONE: 'none',
MOVE: 'move',
RESIZE_NW: 'nw',
RESIZE_NE: 'ne',
RESIZE_SW: 'sw',
RESIZE_SE: 'se',
RESIZE_N: 'n',
RESIZE_S: 's',
RESIZE_E: 'e',
RESIZE_W: 'w',
NEW: 'new'
};
let dragMode = DRAG_MODE.NONE;
let dragOffset = { x: 0, y: 0 };
let originalSelection = null;
const HANDLE_SIZE = 10; // Size of corner/edge handles in canvas pixels
function initCropTool() {
const { cropCanvas, aspectButtons, cropFormatSelect, cropFilenameExt, cropBtn } = elements;
// Format change listener
cropFormatSelect.addEventListener('change', () => {
updateExtensionDisplay(cropFormatSelect, cropFilenameExt);
});
updateExtensionDisplay(cropFormatSelect, cropFilenameExt);
// Aspect ratio buttons
aspectButtons.forEach(btn => {
btn.addEventListener('click', () => {
aspectButtons.forEach(b => b.classList.remove('active'));
btn.classList.add('active');
const ratio = btn.dataset.ratio;
if (ratio === 'free') {
cropAspectRatio = null;
} else {
const [w, h] = ratio.split(':').map(Number);
cropAspectRatio = w / h;
}
// Adjust current selection to new aspect ratio (don't reset)
if (originalImage && cropSelection.width > 0) {
adjustSelectionToAspectRatio();
renderCropCanvas();
}
});
});
// Canvas interaction
cropCanvas.addEventListener('pointerdown', handleCropPointerDown);
cropCanvas.addEventListener('pointermove', handleCropPointerMove);
cropCanvas.addEventListener('pointerup', handleCropPointerUp);
cropCanvas.addEventListener('pointerleave', handleCropPointerUp);
cropBtn.addEventListener('click', () => safeExecute(processCrop, 'Crop'));
}
function adjustSelectionToAspectRatio() {
if (!cropAspectRatio) return;
// Keep center, adjust dimensions
const centerX = cropSelection.x + cropSelection.width / 2;