-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
716 lines (613 loc) · 23.6 KB
/
script.js
File metadata and controls
716 lines (613 loc) · 23.6 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
const dropZone = document.getElementById("drop-zone");
const fileInput = document.getElementById("file-input");
const browseButton = document.getElementById("browse-button");
const statusDiv = document.getElementById("status");
const sourceCanvas = document.getElementById("source-canvas");
const croppedCanvas = document.getElementById("cropped-canvas");
const finalCanvas = document.getElementById("final-canvas");
const previewCanvas = document.getElementById("preview-canvas");
const previewHeading = document.getElementById("preview-heading");
const settingsButton = document.getElementById("settings-button");
const settingsModalOverlay = document.getElementById("settings-modal-overlay");
const settingsModal = document.getElementById("settings-modal");
const closeSettingsButton = document.getElementById("close-settings-button");
const finalSizeInput = document.getElementById("final-size");
const finalSizeValueOutput = document.getElementById("final-size-value");
const finalSizeNumberInput = document.getElementById("final-size-input");
const finalSizeError = document.getElementById("final-size-error");
const marginPercentageInput = document.getElementById("margin-percentage");
const marginPercentageValueOutput = document.getElementById(
"margin-percentage-value"
);
const backgroundColorInput = document.getElementById("background-color");
const resetButtonElements = document.querySelectorAll(".reset-button");
const sourceCtx = sourceCanvas.getContext("2d");
const croppedCtx = croppedCanvas.getContext("2d");
const finalCtx = finalCanvas.getContext("2d");
const previewCtx = previewCanvas.getContext("2d");
// --- Default Settings ---
const DEFAULT_SETTINGS = {
finalSize: 1000, // Square size
marginPercentage: 18, // Margin as % of final size
backgroundColor: "#ffffff",
autoDownload: true, // New setting for automatic download
};
// --- Settings Management ---
let currentSettings = { ...DEFAULT_SETTINGS };
function loadSettings() {
const savedSettings = localStorage.getItem("imageProcessorSettings");
if (savedSettings) {
try {
const parsedSettings = JSON.parse(savedSettings);
// Ensure loaded settings have all keys from defaults, preventing errors if structure changed
currentSettings = { ...DEFAULT_SETTINGS, ...parsedSettings };
// Validate loaded settings (especially ranges)
currentSettings.finalSize = Math.max(
10, // Use correct min
Math.min(
10000, // Use correct max
parseInt(currentSettings.finalSize) || DEFAULT_SETTINGS.finalSize
)
);
currentSettings.marginPercentage = Math.max(
0,
Math.min(
50,
parseInt(currentSettings.marginPercentage) ||
DEFAULT_SETTINGS.marginPercentage
)
);
// Ensure autoDownload is a boolean
currentSettings.autoDownload = !!currentSettings.autoDownload;
} catch (e) {
console.error("Error parsing saved settings:", e);
// Use defaults if parsing fails
currentSettings = { ...DEFAULT_SETTINGS };
}
} else {
currentSettings = { ...DEFAULT_SETTINGS };
}
applySettingsToUI();
}
function saveSettings() {
localStorage.setItem(
"imageProcessorSettings",
JSON.stringify(currentSettings)
);
}
function applySettingsToUI() {
finalSizeInput.value = currentSettings.finalSize;
finalSizeNumberInput.value = currentSettings.finalSize;
finalSizeValueOutput.textContent = `${currentSettings.finalSize} px`;
marginPercentageInput.value = currentSettings.marginPercentage;
marginPercentageValueOutput.textContent = `${currentSettings.marginPercentage} %`;
backgroundColorInput.value = currentSettings.backgroundColor;
// Set the auto-download toggle state
document.getElementById('auto-download').checked = currentSettings.autoDownload;
// Update reset button visibility
updateResetButtonVisibility();
// Update slider track gradient dynamically (optional but nice)
updateSliderTrack(finalSizeInput);
updateSliderTrack(marginPercentageInput);
}
function updateResetButtonVisibility() {
// Check each setting against its default value
const finalSizeResetButton = document.querySelector('[data-setting="finalSize"]');
const marginPercentageResetButton = document.querySelector('[data-setting="marginPercentage"]');
const backgroundColorResetButton = document.querySelector('[data-setting="backgroundColor"]');
finalSizeResetButton.style.display =
currentSettings.finalSize !== DEFAULT_SETTINGS.finalSize ? 'block' : 'none';
marginPercentageResetButton.style.display =
currentSettings.marginPercentage !== DEFAULT_SETTINGS.marginPercentage ? 'block' : 'none';
backgroundColorResetButton.style.display =
currentSettings.backgroundColor !== DEFAULT_SETTINGS.backgroundColor ? 'block' : 'none';
}
function updateSetting(key, value) {
// Basic validation
if (key === "finalSize") {
value = Math.max(10, Math.min(10000, parseInt(value, 10) || DEFAULT_SETTINGS[key]));
} else if (key === "marginPercentage") {
// Allow zero values by checking if value is a number first
const numValue = parseInt(value, 10);
value = isNaN(numValue) ? DEFAULT_SETTINGS[key] : Math.max(0, Math.min(50, numValue));
} else if (key === "backgroundColor") {
// Basic hex color validation (allows 3, 6, 8 digits)
if (!/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/.test(value)) {
value = DEFAULT_SETTINGS[key];
}
}
currentSettings[key] = value;
applySettingsToUI(); // Keep UI in sync (updates slider value text)
saveSettings();
}
function resetSetting(key) {
updateSetting(key, DEFAULT_SETTINGS[key]);
}
// --- Slider Track Styling Update ---
function updateSliderTrack(slider) {
const min = parseFloat(slider.min);
const max = parseFloat(slider.max);
const val = parseFloat(slider.value);
const percentage = ((val - min) * 100) / (max - min);
// Use CSS variables for colors
const activeColor = getComputedStyle(document.documentElement)
.getPropertyValue("--md-primary")
.trim();
const inactiveColor = getComputedStyle(document.documentElement)
.getPropertyValue("--md-surface-variant")
.trim();
slider.style.background = `linear-gradient(to right, ${activeColor} ${percentage}%, ${inactiveColor} ${percentage}%)`;
}
// --- Modal Logic ---
function openSettingsModal() {
applySettingsToUI(); // Ensure UI shows current settings when opened
clearFinalSizeError(); // Clear any previous errors when opening
settingsModalOverlay.classList.add("visible");
}
function closeSettingsModal() {
// **Validation before closing**
const rawValue = finalSizeNumberInput.value;
const value = parseInt(rawValue, 10);
if (isNaN(value) || value < 10 || value > 10000) {
showFinalSizeError("Must be 10 - 10000 px");
return; // Prevent closing
}
// If valid, ensure the potentially manually typed value is saved
clearFinalSizeError();
updateSetting("finalSize", value); // This also updates UI and saves
// Proceed with closing
settingsModalOverlay.classList.remove("visible");
}
// --- Error Handling for Final Size ---
function showFinalSizeError(message) {
finalSizeError.textContent = message;
finalSizeError.style.display = "block";
finalSizeNumberInput.classList.add("error");
}
function clearFinalSizeError() {
finalSizeError.textContent = "";
finalSizeError.style.display = "none";
finalSizeNumberInput.classList.remove("error");
}
// --- Event Listeners for Settings ---
settingsButton.addEventListener("click", openSettingsModal);
closeSettingsButton.addEventListener("click", closeSettingsModal);
settingsModalOverlay.addEventListener("click", (e) => {
// Close if clicked outside the modal dialog itself
if (e.target === settingsModalOverlay) {
// **Also validate when clicking outside**
const rawValue = finalSizeNumberInput.value;
const value = parseInt(rawValue, 10);
if (isNaN(value) || value < 10 || value > 10000) {
showFinalSizeError("Must be 10 - 10000 px");
return; // Prevent closing
}
// If valid, ensure value is saved before closing
clearFinalSizeError();
updateSetting("finalSize", value);
closeSettingsModal(); // Call the original close function (which now handles valid state)
}
});
// Add event listeners for final size inputs
finalSizeInput.addEventListener("input", (e) => {
clearFinalSizeError(); // Clear error when slider moves
const value = parseInt(e.target.value);
if (!isNaN(value)) {
// Update setting directly, validation happens in updateSetting
updateSetting("finalSize", value);
// Sync number input
finalSizeNumberInput.value = value;
}
});
// Add back margin percentage event listener
marginPercentageInput.addEventListener("input", (e) => {
const value = parseInt(e.target.value);
if (!isNaN(value)) {
updateSetting("marginPercentage", value);
updateSliderTrack(e.target); // Update track gradient live
}
});
finalSizeNumberInput.addEventListener("input", (e) => {
clearFinalSizeError(); // Clear error as soon as user types
const rawValue = e.target.value;
const value = parseInt(rawValue, 10);
// Only update slider if the typed value is a valid number within range
if (!isNaN(value) && value >= 10 && value <= 10000) {
finalSizeInput.value = value;
// We only call updateSetting when the slider is moved or modal is closed successfully
// Or should we update immediately if valid? Let's update immediately for better UX.
updateSetting("finalSize", value);
}
// Allow user to type freely, validation happens on close
});
// Use 'change' for color picker (less frequent updates needed)
backgroundColorInput.addEventListener("change", (e) =>
updateSetting("backgroundColor", e.target.value)
);
resetButtonElements.forEach((button) => {
button.addEventListener("click", (e) => {
const settingKey = e.currentTarget.dataset.setting;
if (settingKey) {
resetSetting(settingKey);
// Manually update slider tracks after reset if needed
if (settingKey === "finalSize") updateSliderTrack(finalSizeInput);
if (settingKey === "marginPercentage")
updateSliderTrack(marginPercentageInput);
}
});
});
// Add event listener for auto-download toggle
document.getElementById('auto-download').addEventListener('change', (e) => {
updateSetting('autoDownload', e.target.checked);
});
// Load settings on initial script load
loadSettings();
// --- Material Design Interactive Elements ---
// Ripple effect for buttons (Unchanged)
function createRipple(event) {
const button = event.currentTarget;
// Prevent ripple on slider thumb/track interaction inside the button's parent
if (event.target.type === "range") return;
const ripple = document.createElement("span");
const rect = button.getBoundingClientRect();
// Check if button has icon class for centering ripple
const isIconButton =
button.classList.contains("md-icon-button") ||
button.classList.contains("reset-button");
const size = isIconButton
? Math.max(rect.width, rect.height) * 1.5
: Math.max(rect.width, rect.height) * 2;
const x = event.clientX - rect.left - size / 2;
const y = event.clientY - rect.top - size / 2;
ripple.classList.add("ripple");
ripple.style.width = ripple.style.height = `${size}px`;
ripple.style.left = `${x}px`;
ripple.style.top = `${y}px`;
// Use appropriate ripple color
if (button.classList.contains("md-button")) {
ripple.style.backgroundColor = "rgba(255, 255, 255, 0.5)";
} else {
ripple.style.backgroundColor = "rgba(0, 0, 0, 0.1)"; // Ripple for icon/reset buttons
}
button.appendChild(ripple);
// Remove ripple after animation completes
ripple.addEventListener("animationend", () => {
ripple.remove();
});
}
// Add ripple effect to all MD buttons (includes icon and reset buttons now)
document
.querySelectorAll(".md-button, .md-icon-button, .reset-button")
.forEach((button) => {
button.addEventListener("mousedown", createRipple);
// Add click animation states (optional, can refine)
button.addEventListener("mousedown", () => {
if (button.type !== "range") {
// Don't apply click scale to sliders
button.classList.add("clicked");
}
});
button.addEventListener("mouseup", () => {
setTimeout(() => button.classList.remove("clicked"), 150);
});
button.addEventListener("mouseleave", () => {
button.classList.remove("clicked");
});
});
// Add click animation to drop zone (Unchanged)
dropZone.addEventListener("mousedown", () => {
dropZone.classList.add("clicked");
});
dropZone.addEventListener("mouseup", () => {
setTimeout(() => dropZone.classList.remove("clicked"), 150);
});
dropZone.addEventListener("mouseleave", () => {
dropZone.classList.remove("clicked");
});
// --- Event Handlers ---
// Drag and drop event handlers (Unchanged)
dropZone.addEventListener("dragover", (e) => {
e.preventDefault(); // Prevent default browser behavior
dropZone.classList.add("dragover");
});
dropZone.addEventListener("dragleave", () => {
dropZone.classList.remove("dragover");
});
dropZone.addEventListener("drop", (e) => {
e.preventDefault(); // Prevent default browser behavior
dropZone.classList.remove("dragover");
updateStatus("Processing...", true);
const files = e.dataTransfer.files;
if (files.length > 0) {
handleFile(files[0]);
} else {
updateStatus("No file dropped.");
}
});
// --- Browse Button --- (Unchanged)
browseButton.addEventListener("click", () => {
fileInput.click(); // Trigger the hidden file input
});
fileInput.addEventListener("change", (e) => {
const files = e.target.files;
if (files.length > 0) {
updateStatus("Processing...", true);
handleFile(files[0]);
}
});
// --- Paste Event Handler (Ctrl+V) --- (Unchanged)
document.addEventListener("paste", (e) => {
e.preventDefault();
updateStatus("Processing pasted image...", true);
const items = e.clipboardData.items;
for (let i = 0; i < items.length; i++) {
if (items[i].type.indexOf("image") !== -1) {
const blob = items[i].getAsFile();
// Generate a pseudo-filename for pasted content
blob.name =
"pasted-image-" + new Date().toISOString().replace(/:/g, "-") + ".png"; // Prefer PNG for pasted
handleFile(blob);
return;
}
}
updateStatus("No image found in pasted content.");
});
// --- Status Updates with Animation ---
function updateStatus(message, isProcessing = false) {
statusDiv.textContent = message;
statusDiv.style.display = "block"; // Make status visible
if (isProcessing) {
statusDiv.classList.add("processing");
} else {
statusDiv.classList.remove("processing");
}
}
// --- File Handling --- (Unchanged)
function handleFile(file) {
if (!file.type.startsWith("image/")) {
updateStatus("Error: Dropped file is not an image.");
return;
}
// Store the original filename for later use when downloading
const originalFilename = file.name;
const reader = new FileReader();
reader.onload = function (e) {
const img = new Image();
img.onload = function () {
processImage(img, originalFilename);
};
img.onerror = function () {
updateStatus("Error: Could not load image.");
};
img.src = e.target.result; // Set image source to the loaded file data
};
reader.onerror = function () {
updateStatus("Error: Could not read file.");
};
reader.readAsDataURL(file); // Read the file as a Data URL
}
// --- Image Processing Pipeline ---
function processImage(img, originalFilename) {
updateStatus("Cropping image...", true);
hidePreview(); // Hide previous preview if any
// 1. Crop to Content
const cropData = cropToContent(img);
if (!cropData) {
updateStatus(
"Error: Could not find content in the image (is it all white?)."
);
return;
}
updateStatus("Creating final image...", true);
// 2. Create Final Image (using current settings)
createFinalImage(cropData);
// 3. Draw Preview
drawPreview();
// 4. Handle download based on settings
if (currentSettings.autoDownload) {
downloadImage(originalFilename);
} else {
// Show download button
const downloadButton = document.getElementById('download-button');
downloadButton.style.display = 'block';
downloadButton.onclick = () => {
downloadImage(originalFilename);
downloadButton.style.display = 'none';
};
}
// Show preview with animation
showPreview();
}
function showPreview() {
previewHeading.style.display = "block";
previewCanvas.style.display = "block";
// Hide status message when preview is shown
statusDiv.style.display = "none";
statusDiv.classList.remove("processing");
// Trigger animation
setTimeout(() => {
previewCanvas.classList.add("show");
}, 50); // Short delay to allow display:block to take effect
}
function hidePreview() {
previewHeading.style.display = "none";
previewCanvas.style.display = "none";
previewCanvas.classList.remove("show"); // Reset animation class
}
// --- Step 1: Crop to Content --- (Unchanged)
function cropToContent(img) {
// Draw image onto source canvas to get pixel data
sourceCanvas.width = img.width;
sourceCanvas.height = img.height;
sourceCtx.drawImage(img, 0, 0);
try {
const imageData = sourceCtx.getImageData(
0,
0,
sourceCanvas.width,
sourceCanvas.height
);
const data = imageData.data;
const width = sourceCanvas.width;
const height = sourceCanvas.height;
let minX = width,
minY = height,
maxX = -1,
maxY = -1;
const whiteThreshold = 245; // Pixels with R, G, B > threshold are considered white background
const alphaThreshold = 10; // Pixels with alpha <= threshold are considered transparent background
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const i = (y * width + x) * 4; // Index for the start of pixel data (R, G, B, A)
const r = data[i];
const g = data[i + 1];
const b = data[i + 2];
const a = data[i + 3]; // Alpha channel
// Consider a pixel as content if it's not almost white AND has sufficient alpha
if (
(r <= whiteThreshold || g <= whiteThreshold || b <= whiteThreshold) &&
a > alphaThreshold
) {
if (x < minX) minX = x;
if (x > maxX) maxX = x;
if (y < minY) minY = y;
if (y > maxY) maxY = y;
}
}
}
// Check if any content was found
if (maxX < minX || maxY < minY) {
console.error(
"No content found, image might be entirely white or transparent."
);
return null; // No content found
}
const croppedWidth = maxX - minX + 1;
const croppedHeight = maxY - minY + 1;
// Draw the cropped portion onto the croppedCanvas
croppedCanvas.width = croppedWidth;
croppedCanvas.height = croppedHeight;
croppedCtx.drawImage(
sourceCanvas,
minX,
minY,
croppedWidth,
croppedHeight, // Source rectangle
0,
0,
croppedWidth,
croppedHeight // Destination rectangle
);
console.log(
`Cropped Box: x=${minX}, y=${minY}, w=${croppedWidth}, h=${croppedHeight}`
);
return {
canvas: croppedCanvas,
width: croppedWidth,
height: croppedHeight,
};
} catch (error) {
console.error(
"Error getting image data (maybe CORS issue if loading from external URL):",
error
);
updateStatus("Error processing image data.");
return null;
}
}
// --- Step 2: Create Final Image --- (Updated for new settings)
function createFinalImage(cropData) {
// Use settings from currentSettings
const finalSize = currentSettings.finalSize; // This is both width and height
const marginPercentage = currentSettings.marginPercentage;
const backgroundColor = currentSettings.backgroundColor;
// Calculate absolute margin in pixels
const margin = Math.round(finalSize * (marginPercentage / 100));
// Calculate the available area for the content *after* margins are applied
const targetContentWidth = finalSize - 2 * margin;
const targetContentHeight = finalSize - 2 * margin;
// Ensure target dimensions are positive (margin percentage could be high)
if (targetContentWidth <= 0 || targetContentHeight <= 0) {
console.warn(
"Margin percentage too high, resulting in zero or negative content area. Clamping margin."
);
// Clamp margin calculation if it's too large (e.g., cap content area at 10px)
const maxMargin = Math.floor((finalSize - 10) / 2);
const effectiveMargin = Math.min(margin, maxMargin);
targetContentWidth = finalSize - 2 * effectiveMargin;
targetContentHeight = finalSize - 2 * effectiveMargin;
// Recalculate margin based on clamped area if needed for positioning
// margin = effectiveMargin; // Re-assign margin used for positioning
}
finalCanvas.width = finalSize;
finalCanvas.height = finalSize;
// Fill background with the selected color
finalCtx.fillStyle = backgroundColor;
finalCtx.fillRect(0, 0, finalSize, finalSize);
// Calculate scaling factor to fit cropped image within target area
const scale = Math.min(
targetContentWidth / cropData.width,
targetContentHeight / cropData.height
);
// Calculate dimensions and position to draw the scaled image
const drawWidth = cropData.width * scale;
const drawHeight = cropData.height * scale;
// Calculate top-left corner (drawX, drawY) to center the scaled image within the margin area
const drawX = margin + (targetContentWidth - drawWidth) / 2;
const drawY = margin + (targetContentHeight - drawHeight) / 2;
console.log(
`Final Size: ${finalSize}x${finalSize}, Margin: ${margin}px (${marginPercentage}%)`
);
console.log(
`Target Content Area: ${targetContentWidth}x${targetContentHeight}`
);
console.log(
`Drawing cropped image onto final canvas at: x=${drawX.toFixed(
2
)}, y=${drawY.toFixed(2)}, w=${drawWidth.toFixed(
2
)}, h=${drawHeight.toFixed(2)}, scale: ${scale.toFixed(3)}`
);
// Draw the *cropped* image (from croppedCanvas) onto the final canvas, scaled and positioned
finalCtx.drawImage(cropData.canvas, drawX, drawY, drawWidth, drawHeight);
}
// --- Step 3: Draw Preview --- (Unchanged)
function drawPreview() {
const previewSize = Math.min(500, window.innerWidth - 48); // Adjust preview size based on viewport maybe
previewCanvas.width = previewSize;
previewCanvas.height = previewSize; // Keep preview square
previewCtx.fillStyle =
getComputedStyle(document.documentElement)
.getPropertyValue("--md-surface-variant")
.trim() || "#eee"; // Use theme color for background
previewCtx.fillRect(0, 0, previewCanvas.width, previewCanvas.height);
// Draw the final image (potentially large) onto the smaller preview canvas
// Maintain aspect ratio using drawImage's scaling
previewCtx.drawImage(
finalCanvas,
0,
0, // Source x, y
finalCanvas.width,
finalCanvas.height, // Source width, height
0,
0, // Destination x, y
previewCanvas.width,
previewCanvas.height // Destination width, height
);
}
// --- Step 4: Trigger Download --- (Unchanged)
function downloadImage(originalFilename) {
const dataURL = finalCanvas.toDataURL("image/jpeg", 0.92); // Get image data as JPG with quality setting
const link = document.createElement("a");
link.href = dataURL;
// Sanitize filename and ensure .jpg extension
const baseName = originalFilename.replace(/\.[^/.]+$/, ""); // Remove existing extension
const safeBaseName = baseName.replace(/[^a-z0-9_.\-]/gi, "_"); // Replace unsafe characters
link.download = `${safeBaseName}_${finalCanvas.width}x${finalCanvas.height}.jpg`;
// Append link to body, click it, and remove it
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
// --- Initial UI Setup ---
hidePreview(); // Ensure preview is hidden on load