diff --git a/cmd/image-manipulator/app.js b/cmd/image-manipulator/app.js index a1c7988..24699d3 100644 --- a/cmd/image-manipulator/app.js +++ b/cmd/image-manipulator/app.js @@ -1,6 +1,6 @@ /** * Photoshop Lite · Obsidian Liquid Studio - * Advanced Image Manipulation Suite & Batch Automation + * Professional Image Manipulation Suite & Universal Batch Automation */ // ═══════════════════════════════════════════════════════════════════ @@ -12,20 +12,71 @@ let activeIndex = 0; let zoomFactor = 1.0; let activeSessionId = ""; -// Crop State -let cropAspectRatio = "free"; // "free", "1:1", "16:9", "9:16", "4:5", "4:3", "3:2" -let cropCoords = { x: 0, y: 0, w: 0, h: 0 }; // in CSS pixels relative to image element -let cropInteraction = null; // { mode: 'move' | 'handle', handle: string, startX, startY, origCrop } +// Centralized Tool Parameters State (always available, regardless of active tab) +const toolState = { + crop: { + aspect: "free", + x: 0, y: 0, w: 0, h: 0 + }, + resize: { + width: 0, + height: 0, + maintain_aspect: true + }, + rotate: { + operation: "90", + angle: 0 + }, + adjust: { + brightness: 0, + contrast: 0, + saturation: 0, + gamma: 1.0 + }, + filter: { + filter: "BLUR" + }, + round_corners: { + radius: 35, + is_circle: false + }, + border: { + border_width: 20, + border_color: "#ffffff", + pad_aspect: "none" + }, + watermark: { + position: "bottom_right", + opacity: 60, + base64: "", + fileName: "" + }, + masker: { + brush_size: 35 + }, + convert: { + format: "png", + quality: 95 + }, + compress: { + format: "original", + quality: 80, + target_size_mb: 0 + }, + strip_metadata: { + format: "original", + quality: 95 + } +}; -// Masker State +// Crop Drag State +let cropInteraction = null; + +// Masker Canvas State let maskCanvas = null; let maskCtx = null; let isDrawing = false; let maskStrokes = []; -let brushSize = 35; - -// Watermark Base64 Cache for Batch Processing -let watermarkBase64 = ""; // ═══════════════════════════════════════════════════════════════════ // PROXY-SAFE API URL RESOLVER @@ -45,8 +96,8 @@ document.addEventListener("DOMContentLoaded", () => { setupDragAndDrop(); setupKeyboardShortcuts(); setupCropDragEvents(); - renderToolControls(); renderToolOptions(); + renderToolControls(); updateQueueUI(); }); @@ -137,9 +188,10 @@ function setupDragAndDrop() { function handleFileInputChange(input) { if (input.files && input.files.length > 0) { ingestFiles(input.files); - input.value = ""; // Reset file input + input.value = ""; } } +window.handleFileInputChange = handleFileInputChange; async function ingestFiles(newFileList) { const validFiles = Array.from(newFileList).filter(f => { @@ -180,6 +232,7 @@ async function ingestFiles(newFileList) { updateQueueUI(); showToast(`Loaded ${filesList.length} image(s) into workspace`, "success"); } +window.ingestFiles = ingestFiles; function readFileAsDataURL(file) { return new Promise((resolve) => { @@ -228,6 +281,12 @@ function renderActiveImage() { current.naturalW = imgEl.naturalWidth; current.naturalH = imgEl.naturalHeight; + // Auto-update resize defaults if currently active + if (!toolState.resize.width || toolState.resize.width <= 0) { + toolState.resize.width = current.naturalW; + toolState.resize.height = current.naturalH; + } + updateInspectorInfo(current); setupActiveToolStage(); renderFilmstrip(); @@ -304,6 +363,7 @@ function selectActiveImage(index) { renderActiveImage(); } } +window.selectActiveImage = selectActiveImage; function removeImage(index, event) { if (event) event.stopPropagation(); @@ -314,16 +374,21 @@ function removeImage(index, event) { renderActiveImage(); updateQueueUI(); } +window.removeImage = removeImage; function resetWorkspace() { filesList = []; activeIndex = 0; - cropCoords = { x: 0, y: 0, w: 0, h: 0 }; + toolState.crop.x = 0; + toolState.crop.y = 0; + toolState.crop.w = 0; + toolState.crop.h = 0; maskStrokes = []; renderActiveImage(); updateQueueUI(); showToast("Workspace cleared", "info"); } +window.resetWorkspace = resetWorkspace; function updateInspectorInfo(item) { const fn = document.getElementById("info-filename"); @@ -391,11 +456,15 @@ function setupActiveToolStage() { if (currentTool === "resize" && filesList.length > 0) { const cur = filesList[activeIndex]; - const wIn = document.getElementById("param-width"); - const hIn = document.getElementById("param-height"); - if (wIn && hIn && cur) { - wIn.value = cur.naturalW; - hIn.value = cur.naturalH; + if (cur) { + if (!toolState.resize.width || toolState.resize.width <= 0) { + toolState.resize.width = cur.naturalW; + toolState.resize.height = cur.naturalH; + } + const wIn = document.getElementById("param-width"); + const hIn = document.getElementById("param-height"); + if (wIn) wIn.value = toolState.resize.width; + if (hIn) hIn.value = toolState.resize.height; } } @@ -417,22 +486,29 @@ function initCropBox() { const stageW = img.clientWidth; const stageH = img.clientHeight; - // Initial box: 80% centered + // Initial box: 85% centered const w = Math.round(stageW * 0.85); const h = Math.round(stageH * 0.85); const x = Math.round((stageW - w) / 2); const y = Math.round((stageH - h) / 2); - cropCoords = { x, y, w, h }; - applyAspectRatioConstraint(cropAspectRatio); + toolState.crop.x = x; + toolState.crop.y = y; + toolState.crop.w = w; + toolState.crop.h = h; + + applyAspectRatioConstraint(toolState.crop.aspect); updateCropVisuals(); } function setCropAspect(aspect) { - cropAspectRatio = aspect; + toolState.crop.aspect = aspect; document.querySelectorAll(".crop-aspect-btn").forEach(b => { b.classList.toggle("active", b.getAttribute("data-aspect") === aspect); }); + const aspectSel = document.getElementById("param-crop-aspect"); + if (aspectSel) aspectSel.value = aspect; + applyAspectRatioConstraint(aspect); updateCropVisuals(); } @@ -441,8 +517,11 @@ window.setCropAspect = setCropAspect; function resetCropToFull() { const img = document.getElementById("ps-active-img"); if (!img) return; - cropCoords = { x: 0, y: 0, w: img.clientWidth, h: img.clientHeight }; - applyAspectRatioConstraint(cropAspectRatio); + toolState.crop.x = 0; + toolState.crop.y = 0; + toolState.crop.w = img.clientWidth; + toolState.crop.h = img.clientHeight; + applyAspectRatioConstraint(toolState.crop.aspect); updateCropVisuals(); } window.resetCropToFull = resetCropToFull; @@ -464,7 +543,7 @@ function applyAspectRatioConstraint(aspect) { const targetRatio = ratios[aspect]; if (!targetRatio) return; - let newW = cropCoords.w; + let newW = toolState.crop.w || Math.round(img.clientWidth * 0.85); let newH = Math.round(newW / targetRatio); if (newH > img.clientHeight) { @@ -476,10 +555,10 @@ function applyAspectRatioConstraint(aspect) { newH = Math.round(newW / targetRatio); } - cropCoords.w = newW; - cropCoords.h = newH; - cropCoords.x = Math.max(0, Math.min(img.clientWidth - newW, cropCoords.x)); - cropCoords.y = Math.max(0, Math.min(img.clientHeight - newH, cropCoords.y)); + toolState.crop.w = newW; + toolState.crop.h = newH; + toolState.crop.x = Math.max(0, Math.min(img.clientWidth - newW, toolState.crop.x)); + toolState.crop.y = Math.max(0, Math.min(img.clientHeight - newH, toolState.crop.y)); } function updateCropVisuals() { @@ -493,11 +572,10 @@ function updateCropVisuals() { const sr = document.getElementById("crop-scrim-r"); const dim = document.getElementById("crop-dim-badge"); - const { x, y, w, h } = cropCoords; + const { x, y, w, h } = toolState.crop; const imgW = img.clientWidth; const imgH = img.clientHeight; - // Box position if (box) { box.style.left = `${x}px`; box.style.top = `${y}px`; @@ -505,24 +583,24 @@ function updateCropVisuals() { box.style.height = `${h}px`; } - // Scrims if (st) { st.style.top = "0px"; st.style.left = "0px"; st.style.width = `${imgW}px`; st.style.height = `${y}px`; } if (sb) { sb.style.top = `${y + h}px`; sb.style.left = "0px"; sb.style.width = `${imgW}px`; sb.style.height = `${imgH - (y + h)}px`; } if (sl) { sl.style.top = `${y}px`; sl.style.left = "0px"; sl.style.width = `${x}px`; sl.style.height = `${h}px`; } if (sr) { sr.style.top = `${y}px`; sr.style.left = `${x + w}px`; sr.style.width = `${imgW - (x + w)}px`; sr.style.height = `${h}px`; } - // Actual pixel dimensions - const scaleX = (filesList[activeIndex]?.naturalW || imgW) / imgW; - const scaleY = (filesList[activeIndex]?.naturalH || imgH) / imgH; + const cur = filesList[activeIndex]; + const natW = cur ? cur.naturalW : imgW; + const natH = cur ? cur.naturalH : imgH; + const scaleX = natW / imgW; + const scaleY = natH / imgH; const realW = Math.round(w * scaleX); const realH = Math.round(h * scaleY); if (dim) { - dim.textContent = `${realW} × ${realH} px (${cropAspectRatio})`; + dim.textContent = `${realW} × ${realH} px (${toolState.crop.aspect})`; } - // Sync to header options badge if exists const optBadge = document.getElementById("opt-crop-size"); if (optBadge) { optBadge.textContent = `${realW} × ${realH} px`; @@ -530,8 +608,6 @@ function updateCropVisuals() { } function setupCropDragEvents() { - const box = document.getElementById("crop-box"); - document.addEventListener("mousedown", (e) => { if (currentTool !== "crop") return; const handleEl = e.target.closest(".crop-handle"); @@ -544,7 +620,7 @@ function setupCropDragEvents() { handle: handleEl.getAttribute("data-handle"), startX: e.clientX, startY: e.clientY, - origCrop: { ...cropCoords } + origCrop: { ...toolState.crop } }; } else if (boxEl) { e.preventDefault(); @@ -552,7 +628,7 @@ function setupCropDragEvents() { mode: "move", startX: e.clientX, startY: e.clientY, - origCrop: { ...cropCoords } + origCrop: { ...toolState.crop } }; } }); @@ -576,8 +652,8 @@ function setupCropDragEvents() { newX = Math.max(0, Math.min(imgW - orig.w, newX)); newY = Math.max(0, Math.min(imgH - orig.h, newY)); - cropCoords.x = Math.round(newX); - cropCoords.y = Math.round(newY); + toolState.crop.x = Math.round(newX); + toolState.crop.y = Math.round(newY); updateCropVisuals(); } else if (cropInteraction.mode === "handle") { const h = cropInteraction.handle; @@ -586,16 +662,14 @@ function setupCropDragEvents() { let newW = orig.w; let newH = orig.h; - // Handle directions if (h.includes("e")) newW = orig.w + dx; if (h.includes("s")) newH = orig.h + dy; if (h.includes("w")) { newW = orig.w - dx; newX = orig.x + dx; } if (h.includes("n")) { newH = orig.h - dy; newY = orig.y + dy; } - // Aspect constraint handling - if (cropAspectRatio !== "free") { + if (toolState.crop.aspect !== "free") { const ratios = { "1:1": 1.0, "16:9": 16 / 9, "9:16": 9 / 16, "4:5": 4 / 5, "4:3": 4 / 3, "3:2": 3 / 2 }; - const r = ratios[cropAspectRatio]; + const r = ratios[toolState.crop.aspect]; if (r) { if (h === "e" || h === "w") newH = Math.round(newW / r); else if (h === "n" || h === "s") newW = Math.round(newH * r); @@ -605,10 +679,12 @@ function setupCropDragEvents() { } } - // Minimum constraint if (newW >= 30 && newH >= 30) { if (newX >= 0 && newX + newW <= imgW && newY >= 0 && newY + newH <= imgH) { - cropCoords = { x: Math.round(newX), y: Math.round(newY), w: Math.round(newW), h: Math.round(newH) }; + toolState.crop.x = Math.round(newX); + toolState.crop.y = Math.round(newY); + toolState.crop.w = Math.round(newW); + toolState.crop.h = Math.round(newH); updateCropVisuals(); } } @@ -633,20 +709,19 @@ function initMaskCanvas() { maskCanvas = canvas; maskCtx = canvas.getContext("2d"); - // Re-render strokes if any redrawMaskStrokes(); canvas.onmousedown = (e) => { isDrawing = true; const rect = canvas.getBoundingClientRect(); const pt = { x: e.clientX - rect.left, y: e.clientY - rect.top }; - const stroke = { size: brushSize, points: [pt] }; + const stroke = { size: toolState.masker.brush_size, points: [pt] }; maskStrokes.push(stroke); maskCtx.lineCap = "round"; maskCtx.lineJoin = "round"; maskCtx.strokeStyle = "#ff0000"; - maskCtx.lineWidth = brushSize; + maskCtx.lineWidth = toolState.masker.brush_size; maskCtx.beginPath(); maskCtx.moveTo(pt.x, pt.y); maskCtx.lineTo(pt.x, pt.y); @@ -677,19 +752,19 @@ function initMaskCanvas() { function updateBrushRing(x, y) { const ring = document.getElementById("brush-cursor-ring"); if (!ring) return; + const sz = toolState.masker.brush_size; ring.style.left = `${x}px`; ring.style.top = `${y}px`; - ring.style.width = `${brushSize}px`; - ring.style.height = `${brushSize}px`; + ring.style.width = `${sz}px`; + ring.style.height = `${sz}px`; } function setBrushSize(size) { - brushSize = parseInt(size, 10); - const ring = document.getElementById("brush-cursor-ring"); - if (ring) { - ring.style.width = `${brushSize}px`; - ring.style.height = `${brushSize}px`; - } + toolState.masker.brush_size = parseInt(size, 10); + const optVal = document.getElementById("opt-brush-val"); + const inspVal = document.getElementById("val-brush-sz"); + if (optVal) optVal.innerText = `${size}px`; + if (inspVal) inspVal.innerText = `${size}px`; } window.setBrushSize = setBrushSize; @@ -725,6 +800,36 @@ function redrawMaskStrokes() { }); } +function generateMaskDataUrl(targetW, targetH) { + if (!maskCanvas) return ""; + const outCanvas = document.createElement("canvas"); + outCanvas.width = targetW || maskCanvas.width; + outCanvas.height = targetH || maskCanvas.height; + const ctx = outCanvas.getContext("2d"); + + ctx.fillStyle = "#000000"; + ctx.fillRect(0, 0, outCanvas.width, outCanvas.height); + + const scaleX = outCanvas.width / maskCanvas.width; + const scaleY = outCanvas.height / maskCanvas.height; + + ctx.lineCap = "round"; + ctx.lineJoin = "round"; + ctx.strokeStyle = "#ffffff"; + + maskStrokes.forEach(s => { + ctx.lineWidth = s.size * scaleX; + ctx.beginPath(); + if (s.points.length > 0) { + ctx.moveTo(s.points[0].x * scaleX, s.points[0].y * scaleY); + s.points.forEach(p => ctx.lineTo(p.x * scaleX, p.y * scaleY)); + } + ctx.stroke(); + }); + + return outCanvas.toDataURL("image/png"); +} + // ═══════════════════════════════════════════════════════════════════ // DYNAMIC CONTEXTUAL OPTIONS & INSPECTOR CONTROLS // ═══════════════════════════════════════════════════════════════════ @@ -736,21 +841,22 @@ function renderToolOptions() { crop: `
Aspect: - - - - - - + + + + + +
- + --
`, resize: `
- Scale Presets: + Scale: + @@ -761,21 +867,23 @@ function renderToolOptions() { adjust: `
Presets: - - + + - +
`, filter: `
- Quick Filter: - - - - - - + Filter: + + + + + + + +
`, rotate: ` @@ -791,40 +899,42 @@ function renderToolOptions() { round_corners: `
Radius: - - 35px + + ${toolState.round_corners.radius}px
`, border: `
- Canvas Aspect Pad: - - - - + Aspect Pad: + + + + +
`, watermark: `
- Position: - - - - - + + Anchor: + + + + +
`, masker: `
- Brush Size: - - 35px + Brush: + + ${toolState.masker.brush_size}px
@@ -833,28 +943,28 @@ function renderToolOptions() { `, convert: `
- Target Format: - - - - - - + Format: + + + + + +
`, compress: `
Quality: - - 80% + + ${toolState.compress.quality}%
- Simulating... + Ready
`, strip_metadata: `
- Privacy Guard Active: Strips EXIF, GPS, Camera Model, Timestamps + Privacy Cleaner: EXIF, GPS, Serial Numbers Removed
` }; @@ -876,13 +986,13 @@ function renderToolControls() {
@@ -895,16 +1005,16 @@ function renderToolControls() {
- +
- +
@@ -912,37 +1022,37 @@ function renderToolControls() { adjust: `
Color Grading Sliders
- - + +
- - + +
- - + +
- - + +
`, filter: `
Select Artistic Filter
- + + + + + + + + + +
`, @@ -950,28 +1060,28 @@ function renderToolControls() {
Orientation & Angle
- + + + + +
- - + +
`, round_corners: `
Corner Geometry
- - + +
@@ -979,14 +1089,14 @@ function renderToolControls() { border: `
Border & Canvas Framing
- - + +
- - + +
@@ -999,13 +1109,13 @@ function renderToolControls() {
- + + + + + +
`, @@ -1013,28 +1123,29 @@ function renderToolControls() {
Watermark Stamp
- + + ${toolState.watermark.fileName || 'No file selected yet'}
- + + + + +
- - + +
`, masker: `
Mask Generator & Brush
- - + +

Paint over the foreground object with the red brush. The generated binary mask outputs pure white on a black canvas.

@@ -1044,40 +1155,40 @@ function renderToolControls() {
Transcode Format
- + + + + + + + +
- - + +
`, compress: `
Compression Engine
- + + + +
- - + +
- +
@@ -1097,11 +1208,11 @@ function renderToolControls() {
EXIF Privacy Cleaner
- + + + +
@@ -1118,69 +1229,131 @@ function renderToolControls() { } // ═══════════════════════════════════════════════════════════════════ -// QUICK CONTROLS & RESIZE ASPECT HELPERS +// STATE MUTATORS // ═══════════════════════════════════════════════════════════════════ +function updateResizeWidth(val) { + const w = parseInt(val, 10) || 0; + toolState.resize.width = w; + if (toolState.resize.maintain_aspect && filesList[activeIndex]) { + const cur = filesList[activeIndex]; + const h = Math.round(w * (cur.naturalH / cur.naturalW)); + toolState.resize.height = h; + const hIn = document.getElementById("param-height"); + if (hIn) hIn.value = h; + } +} +window.updateResizeWidth = updateResizeWidth; + +function updateResizeHeight(val) { + const h = parseInt(val, 10) || 0; + toolState.resize.height = h; + if (toolState.resize.maintain_aspect && filesList[activeIndex]) { + const cur = filesList[activeIndex]; + const w = Math.round(h * (cur.naturalW / cur.naturalH)); + toolState.resize.width = w; + const wIn = document.getElementById("param-width"); + if (wIn) wIn.value = w; + } +} +window.updateResizeHeight = updateResizeHeight; + function scaleActiveImage(factor) { const cur = filesList[activeIndex]; if (!cur) return; + const w = Math.round(cur.naturalW * factor); + const h = Math.round(cur.naturalH * factor); + toolState.resize.width = w; + toolState.resize.height = h; const wIn = document.getElementById("param-width"); const hIn = document.getElementById("param-height"); - if (wIn && hIn) { - wIn.value = Math.round(cur.naturalW * factor); - hIn.value = Math.round(cur.naturalH * factor); - } + if (wIn) wIn.value = w; + if (hIn) hIn.value = h; + showToast(`Scaled to ${Math.round(factor * 100)}% (${w}×${h} px)`, "info"); } window.scaleActiveImage = scaleActiveImage; -function syncAspectHeight() { - const maintain = document.getElementById("param-maintain")?.checked; - const cur = filesList[activeIndex]; - if (!maintain || !cur) return; - const w = parseFloat(document.getElementById("param-width").value); - if (w && cur.naturalW) { - document.getElementById("param-height").value = Math.round(w * (cur.naturalH / cur.naturalW)); - } +function updateAdjustParam(key, val, labelId) { + toolState.adjust[key] = parseFloat(val); + const l = document.getElementById(labelId); + if (l) l.innerText = val; } -window.syncAspectHeight = syncAspectHeight; - -function syncAspectWidth() { - const maintain = document.getElementById("param-maintain")?.checked; - const cur = filesList[activeIndex]; - if (!maintain || !cur) return; - const h = parseFloat(document.getElementById("param-height").value); - if (h && cur.naturalH) { - document.getElementById("param-width").value = Math.round(h * (cur.naturalW / cur.naturalH)); - } -} -window.syncAspectWidth = syncAspectWidth; +window.updateAdjustParam = updateAdjustParam; function applyColorPreset(bri, con, sat, gam) { + toolState.adjust.brightness = bri; + toolState.adjust.contrast = con; + toolState.adjust.saturation = sat; + toolState.adjust.gamma = gam; + const bIn = document.getElementById("param-brightness"); const cIn = document.getElementById("param-contrast"); const sIn = document.getElementById("param-saturation"); const gIn = document.getElementById("param-gamma"); + if (bIn) { bIn.value = bri; document.getElementById("val-bri").innerText = bri; } if (cIn) { cIn.value = con; document.getElementById("val-con").innerText = con; } if (sIn) { sIn.value = sat; document.getElementById("val-sat").innerText = sat; } if (gIn) { gIn.value = gam; document.getElementById("val-gam").innerText = gam; } + showToast("Preset applied", "info"); } window.applyColorPreset = applyColorPreset; function setFilterQuick(name) { + toolState.filter.filter = name; const fSelect = document.getElementById("param-filter"); if (fSelect) fSelect.value = name; + renderToolOptions(); executeActiveImage(); } window.setFilterQuick = setFilterQuick; function setRotateQuick(op) { + toolState.rotate.operation = op; const opSelect = document.getElementById("param-operation"); if (opSelect) opSelect.value = op; executeActiveImage(); } window.setRotateQuick = setRotateQuick; +function updateRotateAngle(val) { + toolState.rotate.angle = parseInt(val, 10); + toolState.rotate.operation = val; + const l = document.getElementById("val-angle"); + if (l) l.innerText = `${val}°`; + const op = document.getElementById("param-operation"); + if (op && val !== "0") op.value = val; +} +window.updateRotateAngle = updateRotateAngle; + +function updateRoundRadius(val) { + const r = parseInt(val, 10); + toolState.round_corners.radius = r; + const l1 = document.getElementById("val-radius"); + const l2 = document.getElementById("opt-round-val"); + if (l1) l1.innerText = `${r}px`; + if (l2) l2.innerText = `${r}px`; +} +window.updateRoundRadius = updateRoundRadius; + +function updateCircleAvatar(checked) { + toolState.round_corners.is_circle = checked; + const chk1 = document.getElementById("param-circle"); + const chk2 = document.getElementById("opt-circle-check"); + if (chk1) chk1.checked = checked; + if (chk2) chk2.checked = checked; +} +window.updateCircleAvatar = updateCircleAvatar; + +function updateBorderWidth(val) { + const bw = parseInt(val, 10); + toolState.border.border_width = bw; + const l = document.getElementById("val-bwidth"); + if (l) l.innerText = `${bw}px`; +} +window.updateBorderWidth = updateBorderWidth; + function setCustomBorderColor(hex) { + toolState.border.border_color = hex; const cPicker = document.getElementById("param-border-color"); const cHex = document.getElementById("param-border-color-hex"); if (cPicker) cPicker.value = hex; @@ -1189,33 +1362,84 @@ function setCustomBorderColor(hex) { window.setCustomBorderColor = setCustomBorderColor; function setAspectPad(pad) { + toolState.border.pad_aspect = pad; const pSelect = document.getElementById("param-pad-aspect"); if (pSelect) pSelect.value = pad; + renderToolOptions(); } window.setAspectPad = setAspectPad; +function triggerWatermarkPicker() { + const fileInput = document.getElementById("param-watermark-file"); + if (fileInput) fileInput.click(); +} +window.triggerWatermarkPicker = triggerWatermarkPicker; + +function cacheWatermarkFile(input) { + if (input.files && input.files[0]) { + const file = input.files[0]; + toolState.watermark.fileName = file.name; + const reader = new FileReader(); + reader.onload = (e) => { + toolState.watermark.base64 = e.target.result; + const fLabel = document.getElementById("val-wm-file"); + if (fLabel) fLabel.innerText = file.name; + renderToolOptions(); + showToast(`Watermark selected: ${file.name}`, "success"); + }; + reader.readAsDataURL(file); + } +} +window.cacheWatermarkFile = cacheWatermarkFile; + function setWmPos(pos) { + toolState.watermark.position = pos; const pSelect = document.getElementById("param-position"); if (pSelect) pSelect.value = pos; + renderToolOptions(); } window.setWmPos = setWmPos; +function updateWatermarkOpacity(val) { + const op = parseInt(val, 10); + toolState.watermark.opacity = op; + const l = document.getElementById("val-wm-op"); + if (l) l.innerText = `${op}%`; +} +window.updateWatermarkOpacity = updateWatermarkOpacity; + function setConvertFormat(fmt) { + toolState.convert.format = fmt; const fSelect = document.getElementById("param-format"); if (fSelect) fSelect.value = fmt; + renderToolOptions(); } window.setConvertFormat = setConvertFormat; -function cacheWatermarkBase64(input) { - if (input.files && input.files[0]) { - const reader = new FileReader(); - reader.onload = (e) => { - watermarkBase64 = e.target.result; - }; - reader.readAsDataURL(input.files[0]); - } +function updateConvertQuality(val) { + const q = parseInt(val, 10); + toolState.convert.quality = q; + const l = document.getElementById("val-conv-q"); + if (l) l.innerText = `${q}%`; } -window.cacheWatermarkBase64 = cacheWatermarkBase64; +window.updateConvertQuality = updateConvertQuality; + +function updateCompressFormat(fmt) { + toolState.compress.format = fmt; + simulateCompressionDebounced(); +} +window.updateCompressFormat = updateCompressFormat; + +function updateCompressQuality(val) { + const q = parseInt(val, 10); + toolState.compress.quality = q; + const l1 = document.getElementById("val-comp-q"); + const l2 = document.getElementById("opt-comp-val"); + if (l1) l1.innerText = `${q}%`; + if (l2) l2.innerText = `${q}%`; + simulateCompressionDebounced(); +} +window.updateCompressQuality = updateCompressQuality; // ═══════════════════════════════════════════════════════════════════ // COMPRESSION SIMULATION @@ -1223,7 +1447,7 @@ window.cacheWatermarkBase64 = cacheWatermarkBase64; let simDebounceTimer; function simulateCompressionDebounced() { clearTimeout(simDebounceTimer); - simDebounceTimer = setTimeout(simulateCompression, 400); + simDebounceTimer = setTimeout(simulateCompression, 350); } async function simulateCompression() { @@ -1231,8 +1455,8 @@ async function simulateCompression() { const current = filesList[activeIndex]; if (!current) return; - const quality = document.getElementById("param-quality")?.value || "80"; - const format = document.getElementById("param-format")?.value || "original"; + const quality = toolState.compress.quality.toString(); + const format = toolState.compress.format; const statOrig = document.getElementById("stat-orig-sz"); const statNew = document.getElementById("stat-new-sz"); @@ -1240,7 +1464,7 @@ async function simulateCompression() { const optSim = document.getElementById("opt-comp-sim"); if (statNew) statNew.textContent = "Calculating..."; - if (optSim) optSim.textContent = "Simulating..."; + if (optSim) optSim.textContent = "Calculating..."; try { const formData = new FormData(); @@ -1270,7 +1494,7 @@ async function simulateCompression() { } } catch (err) { if (statNew) statNew.textContent = "Error"; - if (optSim) optSim.textContent = "Simulation error"; + if (optSim) optSim.textContent = "Error"; } } @@ -1286,67 +1510,46 @@ async function executeActiveImage() { const current = filesList[activeIndex]; if (!current) return; - const formData = new FormData(); - // Masker Special Case if (currentTool === "masker") { - if (!maskCanvas) { - showToast("No mask canvas active", "error"); + const maskDataUrl = generateMaskDataUrl(current.naturalW, current.naturalH); + if (!maskDataUrl) { + showToast("Please paint a mask over the object first", "error"); return; } - const outCanvas = document.createElement("canvas"); - outCanvas.width = current.naturalW; - outCanvas.height = current.naturalH; - const ctx = outCanvas.getContext("2d"); - - // Black background - ctx.fillStyle = "#000000"; - ctx.fillRect(0, 0, outCanvas.width, outCanvas.height); - - // Replay in white - const scaleX = current.naturalW / maskCanvas.width; - const scaleY = current.naturalH / maskCanvas.height; - - ctx.lineCap = "round"; - ctx.lineJoin = "round"; - ctx.strokeStyle = "#ffffff"; - - maskStrokes.forEach(s => { - ctx.lineWidth = s.size * scaleX; - ctx.beginPath(); - if (s.points.length > 0) { - ctx.moveTo(s.points[0].x * scaleX, s.points[0].y * scaleY); - s.points.forEach(p => ctx.lineTo(p.x * scaleX, p.y * scaleY)); - } - ctx.stroke(); - }); - - outCanvas.toBlob(async (blob) => { - const fData = new FormData(); - fData.append("images", blob, "mask.png"); - await executeEndpointRequest("/mask", fData); - }, "image/png"); + const maskBlob = await (await fetch(maskDataUrl)).blob(); + const fData = new FormData(); + fData.append("images", maskBlob, "mask.png"); + await executeEndpointRequest("/mask", fData); return; } - // Normal Tools + const formData = new FormData(); formData.append("images", current.file); if (currentTool === "crop") { const img = document.getElementById("ps-active-img"); - const scaleX = current.naturalW / img.clientWidth; - const scaleY = current.naturalH / img.clientHeight; + const imgW = img ? img.clientWidth : current.naturalW; + const imgH = img ? img.clientHeight : current.naturalH; - const l = Math.round(cropCoords.x * scaleX); - const t = Math.round(cropCoords.y * scaleY); - const r = Math.round((cropCoords.x + cropCoords.w) * scaleX); - const b = Math.round((cropCoords.y + cropCoords.h) * scaleY); + let { x, y, w, h } = toolState.crop; + if (!w || !h || w <= 0 || h <= 0) { + x = 0; y = 0; w = imgW; h = imgH; + } - const lPct = (cropCoords.x / img.clientWidth) * 100; - const tPct = (cropCoords.y / img.clientHeight) * 100; - const rPct = ((cropCoords.x + cropCoords.w) / img.clientWidth) * 100; - const bPct = ((cropCoords.y + cropCoords.h) / img.clientHeight) * 100; + const scaleX = current.naturalW / imgW; + const scaleY = current.naturalH / imgH; + + const l = Math.max(0, Math.round(x * scaleX)); + const t = Math.max(0, Math.round(y * scaleY)); + const r = Math.min(current.naturalW, Math.round((x + w) * scaleX)); + const b = Math.min(current.naturalH, Math.round((y + h) * scaleY)); + + const lPct = (x / imgW) * 100; + const tPct = (y / imgH) * 100; + const rPct = ((x + w) / imgW) * 100; + const bPct = ((y + h) / imgH) * 100; formData.append("left", l.toString()); formData.append("top", t.toString()); @@ -1357,42 +1560,50 @@ async function executeActiveImage() { formData.append("right_pct", rPct.toString()); formData.append("bottom_pct", bPct.toString()); } else if (currentTool === "resize") { - formData.append("width", document.getElementById("param-width")?.value || current.naturalW); - formData.append("height", document.getElementById("param-height")?.value || current.naturalH); - formData.append("maintain_aspect", document.getElementById("param-maintain")?.checked ? "true" : "false"); + const w = toolState.resize.width || current.naturalW; + const h = toolState.resize.height || current.naturalH; + formData.append("width", w.toString()); + formData.append("height", h.toString()); + formData.append("maintain_aspect", toolState.resize.maintain_aspect ? "true" : "false"); } else if (currentTool === "adjust") { - formData.append("brightness", document.getElementById("param-brightness")?.value || "0"); - formData.append("contrast", document.getElementById("param-contrast")?.value || "0"); - formData.append("saturation", document.getElementById("param-saturation")?.value || "0"); - formData.append("gamma", document.getElementById("param-gamma")?.value || "1.0"); + formData.append("brightness", toolState.adjust.brightness.toString()); + formData.append("contrast", toolState.adjust.contrast.toString()); + formData.append("saturation", toolState.adjust.saturation.toString()); + formData.append("gamma", toolState.adjust.gamma.toString()); } else if (currentTool === "filter") { - formData.append("filter", document.getElementById("param-filter")?.value || "BLUR"); + formData.append("filter", toolState.filter.filter); } else if (currentTool === "rotate") { - formData.append("operation", document.getElementById("param-operation")?.value || "90"); + formData.append("operation", toolState.rotate.operation); } else if (currentTool === "round_corners") { - formData.append("radius", document.getElementById("param-radius")?.value || "35"); - formData.append("is_circle", document.getElementById("param-circle")?.checked ? "true" : "false"); + formData.append("radius", toolState.round_corners.radius.toString()); + formData.append("is_circle", toolState.round_corners.is_circle ? "true" : "false"); } else if (currentTool === "border") { - formData.append("border_width", document.getElementById("param-border-width")?.value || "20"); - formData.append("border_color", document.getElementById("param-border-color")?.value || "#ffffff"); - formData.append("pad_aspect", document.getElementById("param-pad-aspect")?.value || "none"); + formData.append("border_width", toolState.border.border_width.toString()); + formData.append("border_color", toolState.border.border_color); + formData.append("pad_aspect", toolState.border.pad_aspect); } else if (currentTool === "watermark") { const wmFile = document.getElementById("param-watermark-file")?.files[0]; - if (!wmFile) { + if (wmFile) { + formData.append("watermark", wmFile); + } else if (toolState.watermark.base64) { + formData.append("watermark_base64", toolState.watermark.base64); + } else { showToast("Please choose a watermark image first", "error"); return; } - formData.append("watermark", wmFile); - formData.append("position", document.getElementById("param-position")?.value || "bottom_right"); - formData.append("opacity", document.getElementById("param-opacity")?.value || "60"); + formData.append("position", toolState.watermark.position); + formData.append("opacity", toolState.watermark.opacity.toString()); } else if (currentTool === "convert") { - formData.append("format", document.getElementById("param-format")?.value || "png"); - formData.append("quality", document.getElementById("param-quality")?.value || "95"); + formData.append("format", toolState.convert.format); + formData.append("quality", toolState.convert.quality.toString()); } else if (currentTool === "compress") { - formData.append("quality", document.getElementById("param-quality")?.value || "80"); - formData.append("format", document.getElementById("param-format")?.value || "original"); + formData.append("format", toolState.compress.format); + formData.append("quality", toolState.compress.quality.toString()); + if (toolState.compress.target_size_mb > 0) { + formData.append("target_size_mb", toolState.compress.target_size_mb.toString()); + } } else if (currentTool === "strip_metadata") { - formData.append("format", document.getElementById("param-format")?.value || "original"); + formData.append("format", toolState.strip_metadata.format); formData.append("quality", "95"); } @@ -1424,7 +1635,7 @@ async function executeEndpointRequest(endpoint, formData) { cur.naturalH = resItem.info.height; } - // Re-convert data URI to Blob to update the File reference + // Re-convert data URI to Blob to update File reference const blob = await (await fetch(resItem.image)).blob(); cur.file = new File([blob], resItem.filename || cur.name, { type: blob.type }); cur.size = blob.size; @@ -1440,7 +1651,7 @@ async function executeEndpointRequest(endpoint, formData) { } // ═══════════════════════════════════════════════════════════════════ -// EXECUTE BATCH ALL (Proxy-Safe Chunking & SSE Progress Dashboard) +// EXECUTE BATCH ALL (Universal Batch Across All Tools) // ═══════════════════════════════════════════════════════════════════ async function executeBatchAll() { if (!filesList || filesList.length === 0) { @@ -1458,51 +1669,60 @@ async function executeBatchAll() { if (currentTool === "crop") { const img = document.getElementById("ps-active-img"); - const lPct = (cropCoords.x / img.clientWidth) * 100; - const tPct = (cropCoords.y / img.clientHeight) * 100; - const rPct = ((cropCoords.x + cropCoords.w) / img.clientWidth) * 100; - const bPct = ((cropCoords.y + cropCoords.h) / img.clientHeight) * 100; + const imgW = img ? img.clientWidth : current.naturalW; + const imgH = img ? img.clientHeight : current.naturalH; - params.left_pct = lPct; - params.top_pct = tPct; - params.right_pct = rPct; - params.bottom_pct = bPct; + let { x, y, w, h } = toolState.crop; + if (!w || !h || w <= 0 || h <= 0) { + x = 0; y = 0; w = imgW; h = imgH; + } + + params.left_pct = (x / imgW) * 100; + params.top_pct = (y / imgH) * 100; + params.right_pct = ((x + w) / imgW) * 100; + params.bottom_pct = ((y + h) / imgH) * 100; } else if (currentTool === "resize") { - params.width = parseFloat(document.getElementById("param-width")?.value || current.naturalW); - params.height = parseFloat(document.getElementById("param-height")?.value || current.naturalH); - params.maintain_aspect = document.getElementById("param-maintain")?.checked; + params.width = toolState.resize.width || current.naturalW; + params.height = toolState.resize.height || current.naturalH; + params.maintain_aspect = toolState.resize.maintain_aspect; } else if (currentTool === "adjust") { - params.brightness = parseFloat(document.getElementById("param-brightness")?.value || 0); - params.contrast = parseFloat(document.getElementById("param-contrast")?.value || 0); - params.saturation = parseFloat(document.getElementById("param-saturation")?.value || 0); - params.gamma = parseFloat(document.getElementById("param-gamma")?.value || 1.0); + params.brightness = toolState.adjust.brightness; + params.contrast = toolState.adjust.contrast; + params.saturation = toolState.adjust.saturation; + params.gamma = toolState.adjust.gamma; } else if (currentTool === "filter") { - params.filter = document.getElementById("param-filter")?.value || "BLUR"; + params.filter = toolState.filter.filter; } else if (currentTool === "rotate") { - params.operation = document.getElementById("param-operation")?.value || "90"; + params.operation = toolState.rotate.operation; } else if (currentTool === "round_corners") { - params.radius = parseFloat(document.getElementById("param-radius")?.value || 35); - params.is_circle = document.getElementById("param-circle")?.checked; + params.radius = toolState.round_corners.radius; + params.is_circle = toolState.round_corners.is_circle; } else if (currentTool === "border") { - params.border_width = parseFloat(document.getElementById("param-border-width")?.value || 20); - params.border_color = document.getElementById("param-border-color")?.value || "#ffffff"; - params.pad_aspect = document.getElementById("param-pad-aspect")?.value || "none"; + params.border_width = toolState.border.border_width; + params.border_color = toolState.border.border_color; + params.pad_aspect = toolState.border.pad_aspect; } else if (currentTool === "watermark") { - if (watermarkBase64) { - params.watermark_base64 = watermarkBase64; + if (toolState.watermark.base64) { + params.watermark_base64 = toolState.watermark.base64; + } + params.position = toolState.watermark.position; + params.opacity = toolState.watermark.opacity; + } else if (currentTool === "masker") { + const maskDataUrl = generateMaskDataUrl(current.naturalW, current.naturalH); + if (maskDataUrl) { + params.mask_base64 = maskDataUrl; } - params.position = document.getElementById("param-position")?.value || "bottom_right"; - params.opacity = parseFloat(document.getElementById("param-opacity")?.value || 60); } else if (currentTool === "convert") { - params.format = document.getElementById("param-format")?.value || "png"; - params.quality = parseFloat(document.getElementById("param-quality")?.value || 95); + params.format = toolState.convert.format; + params.quality = toolState.convert.quality; } else if (currentTool === "compress") { - params.format = document.getElementById("param-format")?.value || "original"; - params.quality = parseFloat(document.getElementById("param-quality")?.value || 80); - const targetMb = parseFloat(document.getElementById("param-target-size-mb")?.value || 0); - if (targetMb > 0) params.target_size_mb = targetMb; + params.format = toolState.compress.format; + params.quality = toolState.compress.quality; + if (toolState.compress.target_size_mb > 0) { + params.target_size_mb = toolState.compress.target_size_mb; + } } else if (currentTool === "strip_metadata") { - params.format = document.getElementById("param-format")?.value || "original"; + params.format = toolState.strip_metadata.format; params.quality = 95; } @@ -1537,7 +1757,7 @@ async function executeBatchAll() { for (let i = 0; i < chunks.length; i++) { const chunk = chunks[i]; - const pct = Math.round((i / chunks.length) * 50); // first 50% for upload + const pct = Math.round((i / chunks.length) * 50); updateBatchModalProgress(pct, `Uploading chunk ${i + 1} of ${chunks.length}...`); const fData = new FormData(); @@ -1584,7 +1804,7 @@ async function executeBatchAll() { if (speedEl) speedEl.textContent = `${speedMb.toFixed(1)} MB/s`; } - updateBatchModalProgress(50, "Files uploaded! Starting server-side transformations..."); + updateBatchModalProgress(50, "Files uploaded! Starting server transformations..."); logBatchConsole(`✓ All chunks uploaded successfully. Starting stream processing...`, "success"); // 2. SSE Server-Side Batch Processing @@ -1620,7 +1840,7 @@ async function executeBatchAll() { buffer = lines.pop(); for (const line of lines) { - if (line.startsWith(":")) continue; // Keep-alive ping + if (line.startsWith(":")) continue; if (line.startsWith("data: ")) { try { const ev = JSON.parse(line.substring(6)); @@ -1765,7 +1985,6 @@ function applyZoom() { // ═══════════════════════════════════════════════════════════════════ function setupKeyboardShortcuts() { document.addEventListener("keydown", (e) => { - // If typing in an input or select, skip tool shortcuts if (["INPUT", "SELECT", "TEXTAREA"].includes(e.target.tagName)) { if ((e.ctrlKey || e.metaKey) && e.key === "Enter") { e.preventDefault(); diff --git a/cmd/image-manipulator/handlers1.go b/cmd/image-manipulator/handlers1.go index 6231701..4436092 100644 --- a/cmd/image-manipulator/handlers1.go +++ b/cmd/image-manipulator/handlers1.go @@ -123,12 +123,17 @@ func handleProcessing(w http.ResponseWriter, r *http.Request, processFunc func(i } func resizeHandler(w http.ResponseWriter, r *http.Request) { - width := parseFormInt(r, "width", 800) - height := parseFormInt(r, "height", 600) + width := parseFormInt(r, "width", 0) + height := parseFormInt(r, "height", 0) maintainAspect := r.FormValue("maintain_aspect") == "true" handleProcessing(w, r, func(img image.Image, format string, idx int, filename string) (image.Image, string, float64) { - return resizeImage(img, width, height, maintainAspect), format, 0 + wVal, hVal := width, height + if wVal <= 0 && hVal <= 0 { + wVal = img.Bounds().Dx() + hVal = img.Bounds().Dy() + } + return resizeImage(img, wVal, hVal, maintainAspect), format, 0 }) } @@ -137,6 +142,7 @@ func convertHandler(w http.ResponseWriter, r *http.Request) { if targetFormat == "" { targetFormat = "png" } + quality := parseFormInt(r, "quality", 95) if err := r.ParseMultipartForm(1024 * 1024 * 1024); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) @@ -155,7 +161,8 @@ func convertHandler(w http.ResponseWriter, r *http.Request) { format = "png" } - finalFmt, b64 := imageToBase64(img, targetFormat) + buf, finalFmt := compressLogic(img, targetFormat, quality) + b64 := base64.StdEncoding.EncodeToString(buf) ext := strings.ToLower(finalFmt) if ext == "jpeg" { ext = "jpg" @@ -181,6 +188,7 @@ func convertHandler(w http.ResponseWriter, r *http.Request) { func compressHandler(w http.ResponseWriter, r *http.Request) { quality := parseFormInt(r, "quality", 80) targetFormat := strings.ToLower(r.FormValue("format")) + targetSizeMB := parseFormFloat(r, "target_size_mb", 0) if err := r.ParseMultipartForm(1024 * 1024 * 1024); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) @@ -200,8 +208,43 @@ func compressHandler(w http.ResponseWriter, r *http.Request) { if fmtTarget == "original" || fmtTarget == "" { fmtTarget = format } - - buf, finalFmt := compressLogic(img, fmtTarget, quality) + + var buf []byte + var finalFmt string + origSize := fileHeader.Size + + if targetSizeMB > 0 && origSize > 0 { + targetBytes := int64(targetSizeMB * 1024 * 1024) + ratio := float64(targetBytes) / float64(origSize) + if ratio >= 1.0 { + buf, finalFmt = compressLogic(img, fmtTarget, 92) + } else { + initQ := int(ratio * 90) + if initQ < 10 { initQ = 10 } + if initQ > 90 { initQ = 90 } + trialBuf, trialFmt := compressLogic(img, fmtTarget, initQ) + if int64(len(trialBuf)) <= targetBytes { + buf, finalFmt = trialBuf, trialFmt + } else { + lo, hi := 5, initQ + bestBuf, bestFmt := trialBuf, trialFmt + for iter := 0; iter < 4; iter++ { + mid := (lo + hi) / 2 + tBuf, tFmt := compressLogic(img, fmtTarget, mid) + if int64(len(tBuf)) <= targetBytes { + bestBuf, bestFmt = tBuf, tFmt + lo = mid + 1 + } else { + hi = mid - 1 + } + } + buf, finalFmt = bestBuf, bestFmt + } + } + } else { + buf, finalFmt = compressLogic(img, fmtTarget, quality) + } + b64 := base64.StdEncoding.EncodeToString(buf) sizeKB := float64(len(buf)) / 1024.0 @@ -330,15 +373,21 @@ func watermarkHandler(w http.ResponseWriter, r *http.Request) { return } - wmFile, _, err := r.FormFile("watermark") - if err != nil { - http.Error(w, "No watermark image provided", http.StatusBadRequest) - return + var wmImg image.Image + if wmFile, _, err := r.FormFile("watermark"); err == nil { + wmImg, _, _ = image.Decode(wmFile) + wmFile.Close() + } else if wmBase64 := r.FormValue("watermark_base64"); wmBase64 != "" { + if commaIdx := strings.Index(wmBase64, ","); commaIdx != -1 { + wmBase64 = wmBase64[commaIdx+1:] + } + if decoded, err := base64.StdEncoding.DecodeString(wmBase64); err == nil { + wmImg, _, _ = image.Decode(bytes.NewReader(decoded)) + } } - defer wmFile.Close() - wmImg, _, err := image.Decode(wmFile) - if err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) + + if wmImg == nil { + http.Error(w, "No watermark image provided", http.StatusBadRequest) return } @@ -346,7 +395,7 @@ func watermarkHandler(w http.ResponseWriter, r *http.Request) { if position == "" { position = "bottom_right" } - opacity := parseFormInt(r, "opacity", 50) + opacity := parseFormInt(r, "opacity", 60) files := r.MultipartForm.File["images"] var results []SingleResult diff --git a/cmd/image-manipulator/handlers2.go b/cmd/image-manipulator/handlers2.go index 1570cab..a0373b7 100644 --- a/cmd/image-manipulator/handlers2.go +++ b/cmd/image-manipulator/handlers2.go @@ -6,6 +6,7 @@ import ( "encoding/json" "fmt" "image" + "image/color" _ "image/gif" _ "image/jpeg" _ "image/png" @@ -19,6 +20,7 @@ import ( "sync" "time" + "github.com/disintegration/imaging" _ "golang.org/x/image/bmp" _ "golang.org/x/image/tiff" _ "golang.org/x/image/webp" @@ -211,6 +213,75 @@ func previewBatchHandler(w http.ResponseWriter, r *http.Request) { }) } +func getParamFloat(p map[string]interface{}, key string, def float64) float64 { + if v, ok := p[key]; ok { + switch val := v.(type) { + case float64: + return val + case float32: + return float64(val) + case int: + return float64(val) + case int64: + return float64(val) + case string: + if f, err := strconv.ParseFloat(val, 64); err == nil { + return f + } + } + } + return def +} + +func getParamInt(p map[string]interface{}, key string, def int) int { + if v, ok := p[key]; ok { + switch val := v.(type) { + case float64: + return int(val) + case float32: + return int(val) + case int: + return val + case int64: + return int(val) + case string: + if i, err := strconv.Atoi(val); err == nil { + return i + } + if f, err := strconv.ParseFloat(val, 64); err == nil { + return int(f) + } + } + } + return def +} + +func getParamBool(p map[string]interface{}, key string, def bool) bool { + if v, ok := p[key]; ok { + switch val := v.(type) { + case bool: + return val + case string: + valLower := strings.ToLower(val) + return valLower == "true" || valLower == "1" || valLower == "yes" + case int: + return val != 0 + case float64: + return val != 0 + } + } + return def +} + +func getParamString(p map[string]interface{}, key string, def string) string { + if v, ok := p[key]; ok { + if s, ok := v.(string); ok && s != "" { + return s + } + } + return def +} + func batchProcessSessionHandler(w http.ResponseWriter, r *http.Request) { sessionData := getSessionData(r) @@ -389,35 +460,28 @@ func batchProcessSessionHandler(w http.ResponseWriter, r *http.Request) { switch data.Operation { case "resize": - width := 0 - if w, ok := data.Params["width"].(float64); ok { width = int(w) } - height := 0 - if h, ok := data.Params["height"].(float64); ok { height = int(h) } - maintain := true - if m, ok := data.Params["maintain_aspect"].(bool); ok { maintain = m } - if m, ok := data.Params["maintain"].(bool); ok { maintain = m } + width := getParamInt(data.Params, "width", 0) + height := getParamInt(data.Params, "height", 0) + maintain := getParamBool(data.Params, "maintain_aspect", true) + if !maintain { + maintain = getParamBool(data.Params, "maintain", false) + } processed := resizeImage(img, width, height, maintain) buf, finalFmt = compressLogic(processed, format, 95) case "convert": - targetFmt := "png" - if f, ok := data.Params["format"].(string); ok && f != "" { - targetFmt = f - } - buf, finalFmt = compressLogic(img, targetFmt, 95) + targetFmt := getParamString(data.Params, "format", "png") + quality := getParamInt(data.Params, "quality", 95) + buf, finalFmt = compressLogic(img, targetFmt, quality) case "compress": - targetFmt := format - if f, ok := data.Params["format"].(string); ok && f != "" && f != "original" { - targetFmt = f + targetFmt := getParamString(data.Params, "format", "original") + if targetFmt == "original" { + targetFmt = format } - q := 80 - if qval, ok := data.Params["quality"].(float64); ok { q = int(qval) } + q := getParamInt(data.Params, "quality", 80) // Smart Target Size Compression - var targetSizeMB, currentSizeMB float64 - if t, ok := data.Params["target_size_mb"].(float64); ok { targetSizeMB = t } - if tstr, ok := data.Params["target_size_mb"].(string); ok { targetSizeMB, _ = strconv.ParseFloat(tstr, 64) } - if c, ok := data.Params["current_size_mb"].(float64); ok { currentSizeMB = c } - if cstr, ok := data.Params["current_size_mb"].(string); ok { currentSizeMB, _ = strconv.ParseFloat(cstr, 64) } + targetSizeMB := getParamFloat(data.Params, "target_size_mb", 0) + currentSizeMB := getParamFloat(data.Params, "current_size_mb", 0) if targetSizeMB > 0 && currentSizeMB > 0 { ratio := targetSizeMB / currentSizeMB @@ -464,42 +528,40 @@ func batchProcessSessionHandler(w http.ResponseWriter, r *http.Request) { bounds := img.Bounds() wDx, hDy := float64(bounds.Dx()), float64(bounds.Dy()) l, t, r, b := 0, 0, bounds.Dx(), bounds.Dy() - if lp, ok := data.Params["left_pct"].(float64); ok { - rp, _ := data.Params["right_pct"].(float64) - tp, _ := data.Params["top_pct"].(float64) - bp, _ := data.Params["bottom_pct"].(float64) - if rp > lp && bp > tp { - l = int(wDx * lp / 100.0) - r = int(wDx * rp / 100.0) - t = int(hDy * tp / 100.0) - b = int(hDy * bp / 100.0) - } + lp := getParamFloat(data.Params, "left_pct", -1) + rp := getParamFloat(data.Params, "right_pct", -1) + tp := getParamFloat(data.Params, "top_pct", -1) + bp := getParamFloat(data.Params, "bottom_pct", -1) + + if lp >= 0 && rp > lp && tp >= 0 && bp > tp { + l = int(wDx * lp / 100.0) + r = int(wDx * rp / 100.0) + t = int(hDy * tp / 100.0) + b = int(hDy * bp / 100.0) } else { - if val, ok := data.Params["left"].(float64); ok { l = int(val) } - if val, ok := data.Params["top"].(float64); ok { t = int(val) } - if val, ok := data.Params["right"].(float64); ok { r = int(val) } - if val, ok := data.Params["bottom"].(float64); ok { b = int(val) } + l = getParamInt(data.Params, "left", 0) + t = getParamInt(data.Params, "top", 0) + r = getParamInt(data.Params, "right", bounds.Dx()) + b = getParamInt(data.Params, "bottom", bounds.Dy()) } processed := cropImage(img, l, t, r, b) buf, finalFmt = compressLogic(processed, format, 95) case "filter": - f := "BLUR" - if val, ok := data.Params["filter"].(string); ok && val != "" { f = val } - if val, ok := data.Params["filter_type"].(string); ok && val != "" { f = val } + f := getParamString(data.Params, "filter", "") + if f == "" { + f = getParamString(data.Params, "filter_type", "BLUR") + } processed := filterImage(img, f) buf, finalFmt = compressLogic(processed, format, 95) case "rotate": - op := "90" - if val, ok := data.Params["operation"].(string); ok { op = val } + op := getParamString(data.Params, "operation", "90") processed := rotateImage(img, op) buf, finalFmt = compressLogic(processed, format, 95) case "watermark": - wmPath, _ := data.Params["watermark_path"].(string) - wmBase64, _ := data.Params["watermark_base64"].(string) - pos := "bottom_right" - if p, ok := data.Params["position"].(string); ok && p != "" { pos = p } - op := 50 - if o, ok := data.Params["opacity"].(float64); ok { op = int(o) } + wmPath := getParamString(data.Params, "watermark_path", "") + wmBase64 := getParamString(data.Params, "watermark_base64", "") + pos := getParamString(data.Params, "position", "bottom_right") + op := getParamInt(data.Params, "opacity", 60) var wmImg image.Image if wmBase64 != "" { @@ -520,38 +582,48 @@ func batchProcessSessionHandler(w http.ResponseWriter, r *http.Request) { } buf, finalFmt = compressLogic(img, format, 95) case "adjust": - brightness, contrast, saturation := 0.0, 0.0, 0.0 - gamma := 1.0 - if b, ok := data.Params["brightness"].(float64); ok { brightness = b } - if c, ok := data.Params["contrast"].(float64); ok { contrast = c } - if s, ok := data.Params["saturation"].(float64); ok { saturation = s } - if g, ok := data.Params["gamma"].(float64); ok && g > 0 { gamma = g } + brightness := getParamFloat(data.Params, "brightness", 0.0) + contrast := getParamFloat(data.Params, "contrast", 0.0) + saturation := getParamFloat(data.Params, "saturation", 0.0) + gamma := getParamFloat(data.Params, "gamma", 1.0) processed := adjustColor(img, brightness, contrast, saturation, gamma) buf, finalFmt = compressLogic(processed, format, 95) case "border": - borderWidth := 20 - if bw, ok := data.Params["border_width"].(float64); ok { borderWidth = int(bw) } - borderColor := "#ffffff" - if bc, ok := data.Params["border_color"].(string); ok && bc != "" { borderColor = bc } - padAspect := "" - if pa, ok := data.Params["pad_aspect"].(string); ok { padAspect = pa } + borderWidth := getParamInt(data.Params, "border_width", 20) + borderColor := getParamString(data.Params, "border_color", "#ffffff") + padAspect := getParamString(data.Params, "pad_aspect", "none") processed := addBorderCanvas(img, borderWidth, borderColor, padAspect) buf, finalFmt = compressLogic(processed, format, 95) case "round_corners": - radius := 30 - if r, ok := data.Params["radius"].(float64); ok { radius = int(r) } - isCircle := false - if c, ok := data.Params["is_circle"].(bool); ok { isCircle = c } + radius := getParamInt(data.Params, "radius", 35) + isCircle := getParamBool(data.Params, "is_circle", false) processed := roundCorners(img, radius, isCircle) buf, finalFmt = compressLogic(processed, "PNG", 95) case "strip_metadata": - targetFmt := format - if f, ok := data.Params["format"].(string); ok && f != "" && f != "original" { - targetFmt = f + targetFmt := getParamString(data.Params, "format", "original") + if targetFmt == "original" { + targetFmt = format } - q := 95 - if qval, ok := data.Params["quality"].(float64); ok { q = int(qval) } + q := getParamInt(data.Params, "quality", 95) buf, finalFmt = compressLogic(img, targetFmt, q) + case "masker", "mask": + var maskImg image.Image + maskBase64 := getParamString(data.Params, "mask_base64", "") + if maskBase64 != "" { + if commaIdx := strings.Index(maskBase64, ","); commaIdx != -1 { + maskBase64 = maskBase64[commaIdx+1:] + } + if decoded, err := base64.StdEncoding.DecodeString(maskBase64); err == nil { + maskImg, _, _ = image.Decode(bytes.NewReader(decoded)) + } + } + if maskImg != nil { + resizedMask := imaging.Resize(maskImg, img.Bounds().Dx(), img.Bounds().Dy(), imaging.Lanczos) + buf, finalFmt = compressLogic(resizedMask, "PNG", 95) + } else { + blackCanvas := imaging.New(img.Bounds().Dx(), img.Bounds().Dy(), color.Black) + buf, finalFmt = compressLogic(blackCanvas, "PNG", 95) + } default: buf, finalFmt = compressLogic(img, format, 95) } diff --git a/cmd/image-manipulator/processor.go b/cmd/image-manipulator/processor.go index c0b9cb7..b8f6054 100644 --- a/cmd/image-manipulator/processor.go +++ b/cmd/image-manipulator/processor.go @@ -22,24 +22,27 @@ import ( // ProcessImage applies the specified operation. func resizeImage(img image.Image, width, height int, maintainAspect bool) image.Image { + if width <= 0 && height <= 0 { + return img + } if maintainAspect { if width > 0 && height > 0 { - return imaging.Thumbnail(img, width, height, imaging.Lanczos) + return imaging.Fit(img, width, height, imaging.Lanczos) } - if width > 0 && height == 0 { + if width > 0 && height <= 0 { return imaging.Resize(img, width, 0, imaging.Lanczos) } - if height > 0 && width == 0 { + if height > 0 && width <= 0 { return imaging.Resize(img, 0, height, imaging.Lanczos) } return img } targetW := width - if targetW == 0 { + if targetW <= 0 { targetW = img.Bounds().Dx() } targetH := height - if targetH == 0 { + if targetH <= 0 { targetH = img.Bounds().Dy() } return imaging.Resize(img, targetW, targetH, imaging.Lanczos) @@ -146,10 +149,14 @@ func roundCorners(img image.Image, radius int, isCircle bool) image.Image { bounds := img.Bounds() w, h := bounds.Dx(), bounds.Dy() if isCircle { - radius = w / 2 - if h/2 < radius { - radius = h / 2 + side := w + if h < side { + side = h } + img = imaging.CropCenter(img, side, side) + bounds = img.Bounds() + w, h = bounds.Dx(), bounds.Dy() + radius = side / 2 } if radius <= 0 { return img @@ -261,19 +268,23 @@ func rotateImage(img image.Image, op string) image.Image { func cropImage(img image.Image, left, top, right, bottom int) image.Image { bounds := img.Bounds() + w, h := bounds.Dx(), bounds.Dy() if left < 0 { left = 0 } if top < 0 { top = 0 } - if right > bounds.Dx() { - right = bounds.Dx() + if right > w { + right = w } - if bottom > bounds.Dy() { - bottom = bounds.Dy() + if bottom > h { + bottom = h } - rect := image.Rect(left, top, right, bottom) + if right <= left || bottom <= top { + return img + } + rect := image.Rect(bounds.Min.X+left, bounds.Min.Y+top, bounds.Min.X+right, bounds.Min.Y+bottom) return imaging.Crop(img, rect) } @@ -317,6 +328,19 @@ func watermarkImage(baseImg, watermarkImg image.Image, position string, opacity return result } +func hasTransparency(img image.Image) bool { + bounds := img.Bounds() + for y := bounds.Min.Y; y < bounds.Max.Y; y += 4 { + for x := bounds.Min.X; x < bounds.Max.X; x += 4 { + _, _, _, a := img.At(x, y).RGBA() + if a < 0xFFFF { + return true + } + } + } + return false +} + func encodeExternal(img image.Image, targetFormat string, quality int) ([]byte, error) { var pngBuf bytes.Buffer if err := png.Encode(&pngBuf, img); err != nil { @@ -352,8 +376,19 @@ func encodeExternal(img image.Image, targetFormat string, quality int) ([]byte, from PIL import Image data = sys.stdin.buffer.read() img = Image.open(io.BytesIO(data)) +fmt = '%s' +if fmt in ('JPEG', 'JPG', 'BMP'): + if img.mode in ('RGBA', 'LA', 'P'): + bg = Image.new('RGB', img.size, (255, 255, 255)) + if 'A' in img.mode: + bg.paste(img, mask=img.split()[-1]) + else: + bg.paste(img.convert('RGB')) + img = bg + elif img.mode != 'RGB': + img = img.convert('RGB') out = io.BytesIO() -img.save(out, format='%s', quality=%d) +img.save(out, format=fmt, quality=%d) sys.stdout.buffer.write(out.getvalue()) `, pilFormat, quality) @@ -380,7 +415,12 @@ func compressLogic(img image.Image, targetFormat string, quality int) ([]byte, s var buf bytes.Buffer switch targetFmt { case "JPEG": - if err := jpeg.Encode(&buf, img, &jpeg.Options{Quality: quality}); err == nil { + var rgbImg image.Image = img + if hasTransparency(img) { + whiteBg := imaging.New(img.Bounds().Dx(), img.Bounds().Dy(), color.White) + rgbImg = imaging.Paste(whiteBg, img, image.Pt(0, 0)) + } + if err := jpeg.Encode(&buf, rgbImg, &jpeg.Options{Quality: quality}); err == nil { return buf.Bytes(), "JPEG" } case "PNG": diff --git a/web/image-manipulator/app.js b/web/image-manipulator/app.js index a1c7988..24699d3 100644 --- a/web/image-manipulator/app.js +++ b/web/image-manipulator/app.js @@ -1,6 +1,6 @@ /** * Photoshop Lite · Obsidian Liquid Studio - * Advanced Image Manipulation Suite & Batch Automation + * Professional Image Manipulation Suite & Universal Batch Automation */ // ═══════════════════════════════════════════════════════════════════ @@ -12,20 +12,71 @@ let activeIndex = 0; let zoomFactor = 1.0; let activeSessionId = ""; -// Crop State -let cropAspectRatio = "free"; // "free", "1:1", "16:9", "9:16", "4:5", "4:3", "3:2" -let cropCoords = { x: 0, y: 0, w: 0, h: 0 }; // in CSS pixels relative to image element -let cropInteraction = null; // { mode: 'move' | 'handle', handle: string, startX, startY, origCrop } +// Centralized Tool Parameters State (always available, regardless of active tab) +const toolState = { + crop: { + aspect: "free", + x: 0, y: 0, w: 0, h: 0 + }, + resize: { + width: 0, + height: 0, + maintain_aspect: true + }, + rotate: { + operation: "90", + angle: 0 + }, + adjust: { + brightness: 0, + contrast: 0, + saturation: 0, + gamma: 1.0 + }, + filter: { + filter: "BLUR" + }, + round_corners: { + radius: 35, + is_circle: false + }, + border: { + border_width: 20, + border_color: "#ffffff", + pad_aspect: "none" + }, + watermark: { + position: "bottom_right", + opacity: 60, + base64: "", + fileName: "" + }, + masker: { + brush_size: 35 + }, + convert: { + format: "png", + quality: 95 + }, + compress: { + format: "original", + quality: 80, + target_size_mb: 0 + }, + strip_metadata: { + format: "original", + quality: 95 + } +}; -// Masker State +// Crop Drag State +let cropInteraction = null; + +// Masker Canvas State let maskCanvas = null; let maskCtx = null; let isDrawing = false; let maskStrokes = []; -let brushSize = 35; - -// Watermark Base64 Cache for Batch Processing -let watermarkBase64 = ""; // ═══════════════════════════════════════════════════════════════════ // PROXY-SAFE API URL RESOLVER @@ -45,8 +96,8 @@ document.addEventListener("DOMContentLoaded", () => { setupDragAndDrop(); setupKeyboardShortcuts(); setupCropDragEvents(); - renderToolControls(); renderToolOptions(); + renderToolControls(); updateQueueUI(); }); @@ -137,9 +188,10 @@ function setupDragAndDrop() { function handleFileInputChange(input) { if (input.files && input.files.length > 0) { ingestFiles(input.files); - input.value = ""; // Reset file input + input.value = ""; } } +window.handleFileInputChange = handleFileInputChange; async function ingestFiles(newFileList) { const validFiles = Array.from(newFileList).filter(f => { @@ -180,6 +232,7 @@ async function ingestFiles(newFileList) { updateQueueUI(); showToast(`Loaded ${filesList.length} image(s) into workspace`, "success"); } +window.ingestFiles = ingestFiles; function readFileAsDataURL(file) { return new Promise((resolve) => { @@ -228,6 +281,12 @@ function renderActiveImage() { current.naturalW = imgEl.naturalWidth; current.naturalH = imgEl.naturalHeight; + // Auto-update resize defaults if currently active + if (!toolState.resize.width || toolState.resize.width <= 0) { + toolState.resize.width = current.naturalW; + toolState.resize.height = current.naturalH; + } + updateInspectorInfo(current); setupActiveToolStage(); renderFilmstrip(); @@ -304,6 +363,7 @@ function selectActiveImage(index) { renderActiveImage(); } } +window.selectActiveImage = selectActiveImage; function removeImage(index, event) { if (event) event.stopPropagation(); @@ -314,16 +374,21 @@ function removeImage(index, event) { renderActiveImage(); updateQueueUI(); } +window.removeImage = removeImage; function resetWorkspace() { filesList = []; activeIndex = 0; - cropCoords = { x: 0, y: 0, w: 0, h: 0 }; + toolState.crop.x = 0; + toolState.crop.y = 0; + toolState.crop.w = 0; + toolState.crop.h = 0; maskStrokes = []; renderActiveImage(); updateQueueUI(); showToast("Workspace cleared", "info"); } +window.resetWorkspace = resetWorkspace; function updateInspectorInfo(item) { const fn = document.getElementById("info-filename"); @@ -391,11 +456,15 @@ function setupActiveToolStage() { if (currentTool === "resize" && filesList.length > 0) { const cur = filesList[activeIndex]; - const wIn = document.getElementById("param-width"); - const hIn = document.getElementById("param-height"); - if (wIn && hIn && cur) { - wIn.value = cur.naturalW; - hIn.value = cur.naturalH; + if (cur) { + if (!toolState.resize.width || toolState.resize.width <= 0) { + toolState.resize.width = cur.naturalW; + toolState.resize.height = cur.naturalH; + } + const wIn = document.getElementById("param-width"); + const hIn = document.getElementById("param-height"); + if (wIn) wIn.value = toolState.resize.width; + if (hIn) hIn.value = toolState.resize.height; } } @@ -417,22 +486,29 @@ function initCropBox() { const stageW = img.clientWidth; const stageH = img.clientHeight; - // Initial box: 80% centered + // Initial box: 85% centered const w = Math.round(stageW * 0.85); const h = Math.round(stageH * 0.85); const x = Math.round((stageW - w) / 2); const y = Math.round((stageH - h) / 2); - cropCoords = { x, y, w, h }; - applyAspectRatioConstraint(cropAspectRatio); + toolState.crop.x = x; + toolState.crop.y = y; + toolState.crop.w = w; + toolState.crop.h = h; + + applyAspectRatioConstraint(toolState.crop.aspect); updateCropVisuals(); } function setCropAspect(aspect) { - cropAspectRatio = aspect; + toolState.crop.aspect = aspect; document.querySelectorAll(".crop-aspect-btn").forEach(b => { b.classList.toggle("active", b.getAttribute("data-aspect") === aspect); }); + const aspectSel = document.getElementById("param-crop-aspect"); + if (aspectSel) aspectSel.value = aspect; + applyAspectRatioConstraint(aspect); updateCropVisuals(); } @@ -441,8 +517,11 @@ window.setCropAspect = setCropAspect; function resetCropToFull() { const img = document.getElementById("ps-active-img"); if (!img) return; - cropCoords = { x: 0, y: 0, w: img.clientWidth, h: img.clientHeight }; - applyAspectRatioConstraint(cropAspectRatio); + toolState.crop.x = 0; + toolState.crop.y = 0; + toolState.crop.w = img.clientWidth; + toolState.crop.h = img.clientHeight; + applyAspectRatioConstraint(toolState.crop.aspect); updateCropVisuals(); } window.resetCropToFull = resetCropToFull; @@ -464,7 +543,7 @@ function applyAspectRatioConstraint(aspect) { const targetRatio = ratios[aspect]; if (!targetRatio) return; - let newW = cropCoords.w; + let newW = toolState.crop.w || Math.round(img.clientWidth * 0.85); let newH = Math.round(newW / targetRatio); if (newH > img.clientHeight) { @@ -476,10 +555,10 @@ function applyAspectRatioConstraint(aspect) { newH = Math.round(newW / targetRatio); } - cropCoords.w = newW; - cropCoords.h = newH; - cropCoords.x = Math.max(0, Math.min(img.clientWidth - newW, cropCoords.x)); - cropCoords.y = Math.max(0, Math.min(img.clientHeight - newH, cropCoords.y)); + toolState.crop.w = newW; + toolState.crop.h = newH; + toolState.crop.x = Math.max(0, Math.min(img.clientWidth - newW, toolState.crop.x)); + toolState.crop.y = Math.max(0, Math.min(img.clientHeight - newH, toolState.crop.y)); } function updateCropVisuals() { @@ -493,11 +572,10 @@ function updateCropVisuals() { const sr = document.getElementById("crop-scrim-r"); const dim = document.getElementById("crop-dim-badge"); - const { x, y, w, h } = cropCoords; + const { x, y, w, h } = toolState.crop; const imgW = img.clientWidth; const imgH = img.clientHeight; - // Box position if (box) { box.style.left = `${x}px`; box.style.top = `${y}px`; @@ -505,24 +583,24 @@ function updateCropVisuals() { box.style.height = `${h}px`; } - // Scrims if (st) { st.style.top = "0px"; st.style.left = "0px"; st.style.width = `${imgW}px`; st.style.height = `${y}px`; } if (sb) { sb.style.top = `${y + h}px`; sb.style.left = "0px"; sb.style.width = `${imgW}px`; sb.style.height = `${imgH - (y + h)}px`; } if (sl) { sl.style.top = `${y}px`; sl.style.left = "0px"; sl.style.width = `${x}px`; sl.style.height = `${h}px`; } if (sr) { sr.style.top = `${y}px`; sr.style.left = `${x + w}px`; sr.style.width = `${imgW - (x + w)}px`; sr.style.height = `${h}px`; } - // Actual pixel dimensions - const scaleX = (filesList[activeIndex]?.naturalW || imgW) / imgW; - const scaleY = (filesList[activeIndex]?.naturalH || imgH) / imgH; + const cur = filesList[activeIndex]; + const natW = cur ? cur.naturalW : imgW; + const natH = cur ? cur.naturalH : imgH; + const scaleX = natW / imgW; + const scaleY = natH / imgH; const realW = Math.round(w * scaleX); const realH = Math.round(h * scaleY); if (dim) { - dim.textContent = `${realW} × ${realH} px (${cropAspectRatio})`; + dim.textContent = `${realW} × ${realH} px (${toolState.crop.aspect})`; } - // Sync to header options badge if exists const optBadge = document.getElementById("opt-crop-size"); if (optBadge) { optBadge.textContent = `${realW} × ${realH} px`; @@ -530,8 +608,6 @@ function updateCropVisuals() { } function setupCropDragEvents() { - const box = document.getElementById("crop-box"); - document.addEventListener("mousedown", (e) => { if (currentTool !== "crop") return; const handleEl = e.target.closest(".crop-handle"); @@ -544,7 +620,7 @@ function setupCropDragEvents() { handle: handleEl.getAttribute("data-handle"), startX: e.clientX, startY: e.clientY, - origCrop: { ...cropCoords } + origCrop: { ...toolState.crop } }; } else if (boxEl) { e.preventDefault(); @@ -552,7 +628,7 @@ function setupCropDragEvents() { mode: "move", startX: e.clientX, startY: e.clientY, - origCrop: { ...cropCoords } + origCrop: { ...toolState.crop } }; } }); @@ -576,8 +652,8 @@ function setupCropDragEvents() { newX = Math.max(0, Math.min(imgW - orig.w, newX)); newY = Math.max(0, Math.min(imgH - orig.h, newY)); - cropCoords.x = Math.round(newX); - cropCoords.y = Math.round(newY); + toolState.crop.x = Math.round(newX); + toolState.crop.y = Math.round(newY); updateCropVisuals(); } else if (cropInteraction.mode === "handle") { const h = cropInteraction.handle; @@ -586,16 +662,14 @@ function setupCropDragEvents() { let newW = orig.w; let newH = orig.h; - // Handle directions if (h.includes("e")) newW = orig.w + dx; if (h.includes("s")) newH = orig.h + dy; if (h.includes("w")) { newW = orig.w - dx; newX = orig.x + dx; } if (h.includes("n")) { newH = orig.h - dy; newY = orig.y + dy; } - // Aspect constraint handling - if (cropAspectRatio !== "free") { + if (toolState.crop.aspect !== "free") { const ratios = { "1:1": 1.0, "16:9": 16 / 9, "9:16": 9 / 16, "4:5": 4 / 5, "4:3": 4 / 3, "3:2": 3 / 2 }; - const r = ratios[cropAspectRatio]; + const r = ratios[toolState.crop.aspect]; if (r) { if (h === "e" || h === "w") newH = Math.round(newW / r); else if (h === "n" || h === "s") newW = Math.round(newH * r); @@ -605,10 +679,12 @@ function setupCropDragEvents() { } } - // Minimum constraint if (newW >= 30 && newH >= 30) { if (newX >= 0 && newX + newW <= imgW && newY >= 0 && newY + newH <= imgH) { - cropCoords = { x: Math.round(newX), y: Math.round(newY), w: Math.round(newW), h: Math.round(newH) }; + toolState.crop.x = Math.round(newX); + toolState.crop.y = Math.round(newY); + toolState.crop.w = Math.round(newW); + toolState.crop.h = Math.round(newH); updateCropVisuals(); } } @@ -633,20 +709,19 @@ function initMaskCanvas() { maskCanvas = canvas; maskCtx = canvas.getContext("2d"); - // Re-render strokes if any redrawMaskStrokes(); canvas.onmousedown = (e) => { isDrawing = true; const rect = canvas.getBoundingClientRect(); const pt = { x: e.clientX - rect.left, y: e.clientY - rect.top }; - const stroke = { size: brushSize, points: [pt] }; + const stroke = { size: toolState.masker.brush_size, points: [pt] }; maskStrokes.push(stroke); maskCtx.lineCap = "round"; maskCtx.lineJoin = "round"; maskCtx.strokeStyle = "#ff0000"; - maskCtx.lineWidth = brushSize; + maskCtx.lineWidth = toolState.masker.brush_size; maskCtx.beginPath(); maskCtx.moveTo(pt.x, pt.y); maskCtx.lineTo(pt.x, pt.y); @@ -677,19 +752,19 @@ function initMaskCanvas() { function updateBrushRing(x, y) { const ring = document.getElementById("brush-cursor-ring"); if (!ring) return; + const sz = toolState.masker.brush_size; ring.style.left = `${x}px`; ring.style.top = `${y}px`; - ring.style.width = `${brushSize}px`; - ring.style.height = `${brushSize}px`; + ring.style.width = `${sz}px`; + ring.style.height = `${sz}px`; } function setBrushSize(size) { - brushSize = parseInt(size, 10); - const ring = document.getElementById("brush-cursor-ring"); - if (ring) { - ring.style.width = `${brushSize}px`; - ring.style.height = `${brushSize}px`; - } + toolState.masker.brush_size = parseInt(size, 10); + const optVal = document.getElementById("opt-brush-val"); + const inspVal = document.getElementById("val-brush-sz"); + if (optVal) optVal.innerText = `${size}px`; + if (inspVal) inspVal.innerText = `${size}px`; } window.setBrushSize = setBrushSize; @@ -725,6 +800,36 @@ function redrawMaskStrokes() { }); } +function generateMaskDataUrl(targetW, targetH) { + if (!maskCanvas) return ""; + const outCanvas = document.createElement("canvas"); + outCanvas.width = targetW || maskCanvas.width; + outCanvas.height = targetH || maskCanvas.height; + const ctx = outCanvas.getContext("2d"); + + ctx.fillStyle = "#000000"; + ctx.fillRect(0, 0, outCanvas.width, outCanvas.height); + + const scaleX = outCanvas.width / maskCanvas.width; + const scaleY = outCanvas.height / maskCanvas.height; + + ctx.lineCap = "round"; + ctx.lineJoin = "round"; + ctx.strokeStyle = "#ffffff"; + + maskStrokes.forEach(s => { + ctx.lineWidth = s.size * scaleX; + ctx.beginPath(); + if (s.points.length > 0) { + ctx.moveTo(s.points[0].x * scaleX, s.points[0].y * scaleY); + s.points.forEach(p => ctx.lineTo(p.x * scaleX, p.y * scaleY)); + } + ctx.stroke(); + }); + + return outCanvas.toDataURL("image/png"); +} + // ═══════════════════════════════════════════════════════════════════ // DYNAMIC CONTEXTUAL OPTIONS & INSPECTOR CONTROLS // ═══════════════════════════════════════════════════════════════════ @@ -736,21 +841,22 @@ function renderToolOptions() { crop: `
Aspect: - - - - - - + + + + + +
- + --
`, resize: `
- Scale Presets: + Scale: + @@ -761,21 +867,23 @@ function renderToolOptions() { adjust: `
Presets: - - + + - +
`, filter: `
- Quick Filter: - - - - - - + Filter: + + + + + + + +
`, rotate: ` @@ -791,40 +899,42 @@ function renderToolOptions() { round_corners: `
Radius: - - 35px + + ${toolState.round_corners.radius}px
`, border: `
- Canvas Aspect Pad: - - - - + Aspect Pad: + + + + +
`, watermark: `
- Position: - - - - - + + Anchor: + + + + +
`, masker: `
- Brush Size: - - 35px + Brush: + + ${toolState.masker.brush_size}px
@@ -833,28 +943,28 @@ function renderToolOptions() { `, convert: `
- Target Format: - - - - - - + Format: + + + + + +
`, compress: `
Quality: - - 80% + + ${toolState.compress.quality}%
- Simulating... + Ready
`, strip_metadata: `
- Privacy Guard Active: Strips EXIF, GPS, Camera Model, Timestamps + Privacy Cleaner: EXIF, GPS, Serial Numbers Removed
` }; @@ -876,13 +986,13 @@ function renderToolControls() {
@@ -895,16 +1005,16 @@ function renderToolControls() {
- +
- +
@@ -912,37 +1022,37 @@ function renderToolControls() { adjust: `
Color Grading Sliders
- - + +
- - + +
- - + +
- - + +
`, filter: `
Select Artistic Filter
- + + + + + + + + + +
`, @@ -950,28 +1060,28 @@ function renderToolControls() {
Orientation & Angle
- + + + + +
- - + +
`, round_corners: `
Corner Geometry
- - + +
@@ -979,14 +1089,14 @@ function renderToolControls() { border: `
Border & Canvas Framing
- - + +
- - + +
@@ -999,13 +1109,13 @@ function renderToolControls() {
- + + + + + +
`, @@ -1013,28 +1123,29 @@ function renderToolControls() {
Watermark Stamp
- + + ${toolState.watermark.fileName || 'No file selected yet'}
- + + + + +
- - + +
`, masker: `
Mask Generator & Brush
- - + +

Paint over the foreground object with the red brush. The generated binary mask outputs pure white on a black canvas.

@@ -1044,40 +1155,40 @@ function renderToolControls() {
Transcode Format
- + + + + + + + +
- - + +
`, compress: `
Compression Engine
- + + + +
- - + +
- +
@@ -1097,11 +1208,11 @@ function renderToolControls() {
EXIF Privacy Cleaner
- + + + +
@@ -1118,69 +1229,131 @@ function renderToolControls() { } // ═══════════════════════════════════════════════════════════════════ -// QUICK CONTROLS & RESIZE ASPECT HELPERS +// STATE MUTATORS // ═══════════════════════════════════════════════════════════════════ +function updateResizeWidth(val) { + const w = parseInt(val, 10) || 0; + toolState.resize.width = w; + if (toolState.resize.maintain_aspect && filesList[activeIndex]) { + const cur = filesList[activeIndex]; + const h = Math.round(w * (cur.naturalH / cur.naturalW)); + toolState.resize.height = h; + const hIn = document.getElementById("param-height"); + if (hIn) hIn.value = h; + } +} +window.updateResizeWidth = updateResizeWidth; + +function updateResizeHeight(val) { + const h = parseInt(val, 10) || 0; + toolState.resize.height = h; + if (toolState.resize.maintain_aspect && filesList[activeIndex]) { + const cur = filesList[activeIndex]; + const w = Math.round(h * (cur.naturalW / cur.naturalH)); + toolState.resize.width = w; + const wIn = document.getElementById("param-width"); + if (wIn) wIn.value = w; + } +} +window.updateResizeHeight = updateResizeHeight; + function scaleActiveImage(factor) { const cur = filesList[activeIndex]; if (!cur) return; + const w = Math.round(cur.naturalW * factor); + const h = Math.round(cur.naturalH * factor); + toolState.resize.width = w; + toolState.resize.height = h; const wIn = document.getElementById("param-width"); const hIn = document.getElementById("param-height"); - if (wIn && hIn) { - wIn.value = Math.round(cur.naturalW * factor); - hIn.value = Math.round(cur.naturalH * factor); - } + if (wIn) wIn.value = w; + if (hIn) hIn.value = h; + showToast(`Scaled to ${Math.round(factor * 100)}% (${w}×${h} px)`, "info"); } window.scaleActiveImage = scaleActiveImage; -function syncAspectHeight() { - const maintain = document.getElementById("param-maintain")?.checked; - const cur = filesList[activeIndex]; - if (!maintain || !cur) return; - const w = parseFloat(document.getElementById("param-width").value); - if (w && cur.naturalW) { - document.getElementById("param-height").value = Math.round(w * (cur.naturalH / cur.naturalW)); - } +function updateAdjustParam(key, val, labelId) { + toolState.adjust[key] = parseFloat(val); + const l = document.getElementById(labelId); + if (l) l.innerText = val; } -window.syncAspectHeight = syncAspectHeight; - -function syncAspectWidth() { - const maintain = document.getElementById("param-maintain")?.checked; - const cur = filesList[activeIndex]; - if (!maintain || !cur) return; - const h = parseFloat(document.getElementById("param-height").value); - if (h && cur.naturalH) { - document.getElementById("param-width").value = Math.round(h * (cur.naturalW / cur.naturalH)); - } -} -window.syncAspectWidth = syncAspectWidth; +window.updateAdjustParam = updateAdjustParam; function applyColorPreset(bri, con, sat, gam) { + toolState.adjust.brightness = bri; + toolState.adjust.contrast = con; + toolState.adjust.saturation = sat; + toolState.adjust.gamma = gam; + const bIn = document.getElementById("param-brightness"); const cIn = document.getElementById("param-contrast"); const sIn = document.getElementById("param-saturation"); const gIn = document.getElementById("param-gamma"); + if (bIn) { bIn.value = bri; document.getElementById("val-bri").innerText = bri; } if (cIn) { cIn.value = con; document.getElementById("val-con").innerText = con; } if (sIn) { sIn.value = sat; document.getElementById("val-sat").innerText = sat; } if (gIn) { gIn.value = gam; document.getElementById("val-gam").innerText = gam; } + showToast("Preset applied", "info"); } window.applyColorPreset = applyColorPreset; function setFilterQuick(name) { + toolState.filter.filter = name; const fSelect = document.getElementById("param-filter"); if (fSelect) fSelect.value = name; + renderToolOptions(); executeActiveImage(); } window.setFilterQuick = setFilterQuick; function setRotateQuick(op) { + toolState.rotate.operation = op; const opSelect = document.getElementById("param-operation"); if (opSelect) opSelect.value = op; executeActiveImage(); } window.setRotateQuick = setRotateQuick; +function updateRotateAngle(val) { + toolState.rotate.angle = parseInt(val, 10); + toolState.rotate.operation = val; + const l = document.getElementById("val-angle"); + if (l) l.innerText = `${val}°`; + const op = document.getElementById("param-operation"); + if (op && val !== "0") op.value = val; +} +window.updateRotateAngle = updateRotateAngle; + +function updateRoundRadius(val) { + const r = parseInt(val, 10); + toolState.round_corners.radius = r; + const l1 = document.getElementById("val-radius"); + const l2 = document.getElementById("opt-round-val"); + if (l1) l1.innerText = `${r}px`; + if (l2) l2.innerText = `${r}px`; +} +window.updateRoundRadius = updateRoundRadius; + +function updateCircleAvatar(checked) { + toolState.round_corners.is_circle = checked; + const chk1 = document.getElementById("param-circle"); + const chk2 = document.getElementById("opt-circle-check"); + if (chk1) chk1.checked = checked; + if (chk2) chk2.checked = checked; +} +window.updateCircleAvatar = updateCircleAvatar; + +function updateBorderWidth(val) { + const bw = parseInt(val, 10); + toolState.border.border_width = bw; + const l = document.getElementById("val-bwidth"); + if (l) l.innerText = `${bw}px`; +} +window.updateBorderWidth = updateBorderWidth; + function setCustomBorderColor(hex) { + toolState.border.border_color = hex; const cPicker = document.getElementById("param-border-color"); const cHex = document.getElementById("param-border-color-hex"); if (cPicker) cPicker.value = hex; @@ -1189,33 +1362,84 @@ function setCustomBorderColor(hex) { window.setCustomBorderColor = setCustomBorderColor; function setAspectPad(pad) { + toolState.border.pad_aspect = pad; const pSelect = document.getElementById("param-pad-aspect"); if (pSelect) pSelect.value = pad; + renderToolOptions(); } window.setAspectPad = setAspectPad; +function triggerWatermarkPicker() { + const fileInput = document.getElementById("param-watermark-file"); + if (fileInput) fileInput.click(); +} +window.triggerWatermarkPicker = triggerWatermarkPicker; + +function cacheWatermarkFile(input) { + if (input.files && input.files[0]) { + const file = input.files[0]; + toolState.watermark.fileName = file.name; + const reader = new FileReader(); + reader.onload = (e) => { + toolState.watermark.base64 = e.target.result; + const fLabel = document.getElementById("val-wm-file"); + if (fLabel) fLabel.innerText = file.name; + renderToolOptions(); + showToast(`Watermark selected: ${file.name}`, "success"); + }; + reader.readAsDataURL(file); + } +} +window.cacheWatermarkFile = cacheWatermarkFile; + function setWmPos(pos) { + toolState.watermark.position = pos; const pSelect = document.getElementById("param-position"); if (pSelect) pSelect.value = pos; + renderToolOptions(); } window.setWmPos = setWmPos; +function updateWatermarkOpacity(val) { + const op = parseInt(val, 10); + toolState.watermark.opacity = op; + const l = document.getElementById("val-wm-op"); + if (l) l.innerText = `${op}%`; +} +window.updateWatermarkOpacity = updateWatermarkOpacity; + function setConvertFormat(fmt) { + toolState.convert.format = fmt; const fSelect = document.getElementById("param-format"); if (fSelect) fSelect.value = fmt; + renderToolOptions(); } window.setConvertFormat = setConvertFormat; -function cacheWatermarkBase64(input) { - if (input.files && input.files[0]) { - const reader = new FileReader(); - reader.onload = (e) => { - watermarkBase64 = e.target.result; - }; - reader.readAsDataURL(input.files[0]); - } +function updateConvertQuality(val) { + const q = parseInt(val, 10); + toolState.convert.quality = q; + const l = document.getElementById("val-conv-q"); + if (l) l.innerText = `${q}%`; } -window.cacheWatermarkBase64 = cacheWatermarkBase64; +window.updateConvertQuality = updateConvertQuality; + +function updateCompressFormat(fmt) { + toolState.compress.format = fmt; + simulateCompressionDebounced(); +} +window.updateCompressFormat = updateCompressFormat; + +function updateCompressQuality(val) { + const q = parseInt(val, 10); + toolState.compress.quality = q; + const l1 = document.getElementById("val-comp-q"); + const l2 = document.getElementById("opt-comp-val"); + if (l1) l1.innerText = `${q}%`; + if (l2) l2.innerText = `${q}%`; + simulateCompressionDebounced(); +} +window.updateCompressQuality = updateCompressQuality; // ═══════════════════════════════════════════════════════════════════ // COMPRESSION SIMULATION @@ -1223,7 +1447,7 @@ window.cacheWatermarkBase64 = cacheWatermarkBase64; let simDebounceTimer; function simulateCompressionDebounced() { clearTimeout(simDebounceTimer); - simDebounceTimer = setTimeout(simulateCompression, 400); + simDebounceTimer = setTimeout(simulateCompression, 350); } async function simulateCompression() { @@ -1231,8 +1455,8 @@ async function simulateCompression() { const current = filesList[activeIndex]; if (!current) return; - const quality = document.getElementById("param-quality")?.value || "80"; - const format = document.getElementById("param-format")?.value || "original"; + const quality = toolState.compress.quality.toString(); + const format = toolState.compress.format; const statOrig = document.getElementById("stat-orig-sz"); const statNew = document.getElementById("stat-new-sz"); @@ -1240,7 +1464,7 @@ async function simulateCompression() { const optSim = document.getElementById("opt-comp-sim"); if (statNew) statNew.textContent = "Calculating..."; - if (optSim) optSim.textContent = "Simulating..."; + if (optSim) optSim.textContent = "Calculating..."; try { const formData = new FormData(); @@ -1270,7 +1494,7 @@ async function simulateCompression() { } } catch (err) { if (statNew) statNew.textContent = "Error"; - if (optSim) optSim.textContent = "Simulation error"; + if (optSim) optSim.textContent = "Error"; } } @@ -1286,67 +1510,46 @@ async function executeActiveImage() { const current = filesList[activeIndex]; if (!current) return; - const formData = new FormData(); - // Masker Special Case if (currentTool === "masker") { - if (!maskCanvas) { - showToast("No mask canvas active", "error"); + const maskDataUrl = generateMaskDataUrl(current.naturalW, current.naturalH); + if (!maskDataUrl) { + showToast("Please paint a mask over the object first", "error"); return; } - const outCanvas = document.createElement("canvas"); - outCanvas.width = current.naturalW; - outCanvas.height = current.naturalH; - const ctx = outCanvas.getContext("2d"); - - // Black background - ctx.fillStyle = "#000000"; - ctx.fillRect(0, 0, outCanvas.width, outCanvas.height); - - // Replay in white - const scaleX = current.naturalW / maskCanvas.width; - const scaleY = current.naturalH / maskCanvas.height; - - ctx.lineCap = "round"; - ctx.lineJoin = "round"; - ctx.strokeStyle = "#ffffff"; - - maskStrokes.forEach(s => { - ctx.lineWidth = s.size * scaleX; - ctx.beginPath(); - if (s.points.length > 0) { - ctx.moveTo(s.points[0].x * scaleX, s.points[0].y * scaleY); - s.points.forEach(p => ctx.lineTo(p.x * scaleX, p.y * scaleY)); - } - ctx.stroke(); - }); - - outCanvas.toBlob(async (blob) => { - const fData = new FormData(); - fData.append("images", blob, "mask.png"); - await executeEndpointRequest("/mask", fData); - }, "image/png"); + const maskBlob = await (await fetch(maskDataUrl)).blob(); + const fData = new FormData(); + fData.append("images", maskBlob, "mask.png"); + await executeEndpointRequest("/mask", fData); return; } - // Normal Tools + const formData = new FormData(); formData.append("images", current.file); if (currentTool === "crop") { const img = document.getElementById("ps-active-img"); - const scaleX = current.naturalW / img.clientWidth; - const scaleY = current.naturalH / img.clientHeight; + const imgW = img ? img.clientWidth : current.naturalW; + const imgH = img ? img.clientHeight : current.naturalH; - const l = Math.round(cropCoords.x * scaleX); - const t = Math.round(cropCoords.y * scaleY); - const r = Math.round((cropCoords.x + cropCoords.w) * scaleX); - const b = Math.round((cropCoords.y + cropCoords.h) * scaleY); + let { x, y, w, h } = toolState.crop; + if (!w || !h || w <= 0 || h <= 0) { + x = 0; y = 0; w = imgW; h = imgH; + } - const lPct = (cropCoords.x / img.clientWidth) * 100; - const tPct = (cropCoords.y / img.clientHeight) * 100; - const rPct = ((cropCoords.x + cropCoords.w) / img.clientWidth) * 100; - const bPct = ((cropCoords.y + cropCoords.h) / img.clientHeight) * 100; + const scaleX = current.naturalW / imgW; + const scaleY = current.naturalH / imgH; + + const l = Math.max(0, Math.round(x * scaleX)); + const t = Math.max(0, Math.round(y * scaleY)); + const r = Math.min(current.naturalW, Math.round((x + w) * scaleX)); + const b = Math.min(current.naturalH, Math.round((y + h) * scaleY)); + + const lPct = (x / imgW) * 100; + const tPct = (y / imgH) * 100; + const rPct = ((x + w) / imgW) * 100; + const bPct = ((y + h) / imgH) * 100; formData.append("left", l.toString()); formData.append("top", t.toString()); @@ -1357,42 +1560,50 @@ async function executeActiveImage() { formData.append("right_pct", rPct.toString()); formData.append("bottom_pct", bPct.toString()); } else if (currentTool === "resize") { - formData.append("width", document.getElementById("param-width")?.value || current.naturalW); - formData.append("height", document.getElementById("param-height")?.value || current.naturalH); - formData.append("maintain_aspect", document.getElementById("param-maintain")?.checked ? "true" : "false"); + const w = toolState.resize.width || current.naturalW; + const h = toolState.resize.height || current.naturalH; + formData.append("width", w.toString()); + formData.append("height", h.toString()); + formData.append("maintain_aspect", toolState.resize.maintain_aspect ? "true" : "false"); } else if (currentTool === "adjust") { - formData.append("brightness", document.getElementById("param-brightness")?.value || "0"); - formData.append("contrast", document.getElementById("param-contrast")?.value || "0"); - formData.append("saturation", document.getElementById("param-saturation")?.value || "0"); - formData.append("gamma", document.getElementById("param-gamma")?.value || "1.0"); + formData.append("brightness", toolState.adjust.brightness.toString()); + formData.append("contrast", toolState.adjust.contrast.toString()); + formData.append("saturation", toolState.adjust.saturation.toString()); + formData.append("gamma", toolState.adjust.gamma.toString()); } else if (currentTool === "filter") { - formData.append("filter", document.getElementById("param-filter")?.value || "BLUR"); + formData.append("filter", toolState.filter.filter); } else if (currentTool === "rotate") { - formData.append("operation", document.getElementById("param-operation")?.value || "90"); + formData.append("operation", toolState.rotate.operation); } else if (currentTool === "round_corners") { - formData.append("radius", document.getElementById("param-radius")?.value || "35"); - formData.append("is_circle", document.getElementById("param-circle")?.checked ? "true" : "false"); + formData.append("radius", toolState.round_corners.radius.toString()); + formData.append("is_circle", toolState.round_corners.is_circle ? "true" : "false"); } else if (currentTool === "border") { - formData.append("border_width", document.getElementById("param-border-width")?.value || "20"); - formData.append("border_color", document.getElementById("param-border-color")?.value || "#ffffff"); - formData.append("pad_aspect", document.getElementById("param-pad-aspect")?.value || "none"); + formData.append("border_width", toolState.border.border_width.toString()); + formData.append("border_color", toolState.border.border_color); + formData.append("pad_aspect", toolState.border.pad_aspect); } else if (currentTool === "watermark") { const wmFile = document.getElementById("param-watermark-file")?.files[0]; - if (!wmFile) { + if (wmFile) { + formData.append("watermark", wmFile); + } else if (toolState.watermark.base64) { + formData.append("watermark_base64", toolState.watermark.base64); + } else { showToast("Please choose a watermark image first", "error"); return; } - formData.append("watermark", wmFile); - formData.append("position", document.getElementById("param-position")?.value || "bottom_right"); - formData.append("opacity", document.getElementById("param-opacity")?.value || "60"); + formData.append("position", toolState.watermark.position); + formData.append("opacity", toolState.watermark.opacity.toString()); } else if (currentTool === "convert") { - formData.append("format", document.getElementById("param-format")?.value || "png"); - formData.append("quality", document.getElementById("param-quality")?.value || "95"); + formData.append("format", toolState.convert.format); + formData.append("quality", toolState.convert.quality.toString()); } else if (currentTool === "compress") { - formData.append("quality", document.getElementById("param-quality")?.value || "80"); - formData.append("format", document.getElementById("param-format")?.value || "original"); + formData.append("format", toolState.compress.format); + formData.append("quality", toolState.compress.quality.toString()); + if (toolState.compress.target_size_mb > 0) { + formData.append("target_size_mb", toolState.compress.target_size_mb.toString()); + } } else if (currentTool === "strip_metadata") { - formData.append("format", document.getElementById("param-format")?.value || "original"); + formData.append("format", toolState.strip_metadata.format); formData.append("quality", "95"); } @@ -1424,7 +1635,7 @@ async function executeEndpointRequest(endpoint, formData) { cur.naturalH = resItem.info.height; } - // Re-convert data URI to Blob to update the File reference + // Re-convert data URI to Blob to update File reference const blob = await (await fetch(resItem.image)).blob(); cur.file = new File([blob], resItem.filename || cur.name, { type: blob.type }); cur.size = blob.size; @@ -1440,7 +1651,7 @@ async function executeEndpointRequest(endpoint, formData) { } // ═══════════════════════════════════════════════════════════════════ -// EXECUTE BATCH ALL (Proxy-Safe Chunking & SSE Progress Dashboard) +// EXECUTE BATCH ALL (Universal Batch Across All Tools) // ═══════════════════════════════════════════════════════════════════ async function executeBatchAll() { if (!filesList || filesList.length === 0) { @@ -1458,51 +1669,60 @@ async function executeBatchAll() { if (currentTool === "crop") { const img = document.getElementById("ps-active-img"); - const lPct = (cropCoords.x / img.clientWidth) * 100; - const tPct = (cropCoords.y / img.clientHeight) * 100; - const rPct = ((cropCoords.x + cropCoords.w) / img.clientWidth) * 100; - const bPct = ((cropCoords.y + cropCoords.h) / img.clientHeight) * 100; + const imgW = img ? img.clientWidth : current.naturalW; + const imgH = img ? img.clientHeight : current.naturalH; - params.left_pct = lPct; - params.top_pct = tPct; - params.right_pct = rPct; - params.bottom_pct = bPct; + let { x, y, w, h } = toolState.crop; + if (!w || !h || w <= 0 || h <= 0) { + x = 0; y = 0; w = imgW; h = imgH; + } + + params.left_pct = (x / imgW) * 100; + params.top_pct = (y / imgH) * 100; + params.right_pct = ((x + w) / imgW) * 100; + params.bottom_pct = ((y + h) / imgH) * 100; } else if (currentTool === "resize") { - params.width = parseFloat(document.getElementById("param-width")?.value || current.naturalW); - params.height = parseFloat(document.getElementById("param-height")?.value || current.naturalH); - params.maintain_aspect = document.getElementById("param-maintain")?.checked; + params.width = toolState.resize.width || current.naturalW; + params.height = toolState.resize.height || current.naturalH; + params.maintain_aspect = toolState.resize.maintain_aspect; } else if (currentTool === "adjust") { - params.brightness = parseFloat(document.getElementById("param-brightness")?.value || 0); - params.contrast = parseFloat(document.getElementById("param-contrast")?.value || 0); - params.saturation = parseFloat(document.getElementById("param-saturation")?.value || 0); - params.gamma = parseFloat(document.getElementById("param-gamma")?.value || 1.0); + params.brightness = toolState.adjust.brightness; + params.contrast = toolState.adjust.contrast; + params.saturation = toolState.adjust.saturation; + params.gamma = toolState.adjust.gamma; } else if (currentTool === "filter") { - params.filter = document.getElementById("param-filter")?.value || "BLUR"; + params.filter = toolState.filter.filter; } else if (currentTool === "rotate") { - params.operation = document.getElementById("param-operation")?.value || "90"; + params.operation = toolState.rotate.operation; } else if (currentTool === "round_corners") { - params.radius = parseFloat(document.getElementById("param-radius")?.value || 35); - params.is_circle = document.getElementById("param-circle")?.checked; + params.radius = toolState.round_corners.radius; + params.is_circle = toolState.round_corners.is_circle; } else if (currentTool === "border") { - params.border_width = parseFloat(document.getElementById("param-border-width")?.value || 20); - params.border_color = document.getElementById("param-border-color")?.value || "#ffffff"; - params.pad_aspect = document.getElementById("param-pad-aspect")?.value || "none"; + params.border_width = toolState.border.border_width; + params.border_color = toolState.border.border_color; + params.pad_aspect = toolState.border.pad_aspect; } else if (currentTool === "watermark") { - if (watermarkBase64) { - params.watermark_base64 = watermarkBase64; + if (toolState.watermark.base64) { + params.watermark_base64 = toolState.watermark.base64; + } + params.position = toolState.watermark.position; + params.opacity = toolState.watermark.opacity; + } else if (currentTool === "masker") { + const maskDataUrl = generateMaskDataUrl(current.naturalW, current.naturalH); + if (maskDataUrl) { + params.mask_base64 = maskDataUrl; } - params.position = document.getElementById("param-position")?.value || "bottom_right"; - params.opacity = parseFloat(document.getElementById("param-opacity")?.value || 60); } else if (currentTool === "convert") { - params.format = document.getElementById("param-format")?.value || "png"; - params.quality = parseFloat(document.getElementById("param-quality")?.value || 95); + params.format = toolState.convert.format; + params.quality = toolState.convert.quality; } else if (currentTool === "compress") { - params.format = document.getElementById("param-format")?.value || "original"; - params.quality = parseFloat(document.getElementById("param-quality")?.value || 80); - const targetMb = parseFloat(document.getElementById("param-target-size-mb")?.value || 0); - if (targetMb > 0) params.target_size_mb = targetMb; + params.format = toolState.compress.format; + params.quality = toolState.compress.quality; + if (toolState.compress.target_size_mb > 0) { + params.target_size_mb = toolState.compress.target_size_mb; + } } else if (currentTool === "strip_metadata") { - params.format = document.getElementById("param-format")?.value || "original"; + params.format = toolState.strip_metadata.format; params.quality = 95; } @@ -1537,7 +1757,7 @@ async function executeBatchAll() { for (let i = 0; i < chunks.length; i++) { const chunk = chunks[i]; - const pct = Math.round((i / chunks.length) * 50); // first 50% for upload + const pct = Math.round((i / chunks.length) * 50); updateBatchModalProgress(pct, `Uploading chunk ${i + 1} of ${chunks.length}...`); const fData = new FormData(); @@ -1584,7 +1804,7 @@ async function executeBatchAll() { if (speedEl) speedEl.textContent = `${speedMb.toFixed(1)} MB/s`; } - updateBatchModalProgress(50, "Files uploaded! Starting server-side transformations..."); + updateBatchModalProgress(50, "Files uploaded! Starting server transformations..."); logBatchConsole(`✓ All chunks uploaded successfully. Starting stream processing...`, "success"); // 2. SSE Server-Side Batch Processing @@ -1620,7 +1840,7 @@ async function executeBatchAll() { buffer = lines.pop(); for (const line of lines) { - if (line.startsWith(":")) continue; // Keep-alive ping + if (line.startsWith(":")) continue; if (line.startsWith("data: ")) { try { const ev = JSON.parse(line.substring(6)); @@ -1765,7 +1985,6 @@ function applyZoom() { // ═══════════════════════════════════════════════════════════════════ function setupKeyboardShortcuts() { document.addEventListener("keydown", (e) => { - // If typing in an input or select, skip tool shortcuts if (["INPUT", "SELECT", "TEXTAREA"].includes(e.target.tagName)) { if ((e.ctrlKey || e.metaKey) && e.key === "Enter") { e.preventDefault();