diff --git a/src/pixelflow/api/app.py b/src/pixelflow/api/app.py index 5bdb54d..e38ad57 100644 --- a/src/pixelflow/api/app.py +++ b/src/pixelflow/api/app.py @@ -146,8 +146,11 @@ async def process_image_endpoint( pipeline: Annotated[str, Form(...)], settings: Annotated[ApiSettings, Depends(get_api_settings)], output_format: Annotated[str | None, Form()] = None, + quality: Annotated[int | None, Form()] = None, ) -> Response: - return await _handle_process_request(image, pipeline, settings, output_format) + return await _handle_process_request( + image, pipeline, settings, output_format, quality + ) @app.post("/v1/process-multipage") async def process_multipage_endpoint( @@ -265,6 +268,7 @@ async def _handle_process_request( pipeline_text: str, settings: ApiSettings, output_format: str | None = None, + quality: int | None = None, ) -> Response: content_type = (upload.content_type or "").lower().strip() if content_type not in settings.allowed_mime_types: @@ -284,7 +288,9 @@ async def _handle_process_request( if target_format == "JPG": target_format = "JPEG" output_media = FORMAT_TO_MIME.get(target_format, content_type) - output_bytes = encode_image_bytes(processed, image_format=target_format) + output_bytes = encode_image_bytes( + processed, image_format=target_format, quality=quality + ) return Response(content=output_bytes, media_type=output_media) diff --git a/src/pixelflow/api/static/index.html b/src/pixelflow/api/static/index.html index c6b2f2d..996d4ae 100644 --- a/src/pixelflow/api/static/index.html +++ b/src/pixelflow/api/static/index.html @@ -1783,6 +1783,12 @@ + + + + + + + + +
+ Hazır. +
+ + +
+
+ + +
@@ -5344,6 +5448,208 @@

{ + if (!loupeActive || img.style.display === "none" || !img.src) { + loupeEl.style.display = "none"; + return; + } + + const rect = img.getBoundingClientRect(); + if (e.clientX < rect.left || e.clientX > rect.right || e.clientY < rect.top || e.clientY > rect.bottom) { + loupeEl.style.display = "none"; + return; + } + + loupeEl.style.display = "block"; + const boxRect = box.getBoundingClientRect(); + const posX = e.clientX - boxRect.left; + const posY = e.clientY - boxRect.top; + loupeEl.style.left = posX + "px"; + loupeEl.style.top = posY + "px"; + + const natW = img.naturalWidth || img.width || 1; + const natH = img.naturalHeight || img.height || 1; + const scaleX = natW / rect.width; + const scaleY = natH / rect.height; + const natX = Math.floor((e.clientX - rect.left) * scaleX); + const natY = Math.floor((e.clientY - rect.top) * scaleY); + + const sampleSize = 18; + const half = Math.floor(sampleSize / 2); + const sx = Math.max(0, Math.min(natW - sampleSize, natX - half)); + const sy = Math.max(0, Math.min(natH - sampleSize, natY - half)); + + ctx.clearRect(0, 0, 150, 150); + try { + ctx.drawImage(img, sx, sy, sampleSize, sampleSize, 0, 0, 150, 150); + + ctx.strokeStyle = "rgba(255, 255, 255, 0.15)"; + ctx.lineWidth = 0.5; + const step = 150 / sampleSize; + for (let i = 0; i <= 150; i += step) { + ctx.beginPath(); ctx.moveTo(i, 0); ctx.lineTo(i, 150); ctx.stroke(); + ctx.beginPath(); ctx.moveTo(0, i); ctx.lineTo(150, i); ctx.stroke(); + } + + const centerData = ctx.getImageData(75, 75, 1, 1).data; + const r = centerData[0], g = centerData[1], b = centerData[2]; + const hex = "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1).toUpperCase(); + currentLoupeHex = hex; + + if (loupeHex) loupeHex.textContent = hex; + if (loupeSwatch) loupeSwatch.style.backgroundColor = hex; + } catch (err) {} + }); + + box.addEventListener("mouseleave", () => { + if (loupeEl) loupeEl.style.display = "none"; + }); + + box.addEventListener("click", () => { + if (loupeActive && currentLoupeHex) { + navigator.clipboard.writeText(currentLoupeHex); + statusMessage.textContent = currentLang === "en" ? `✓ Copied hex: ${currentLoupeHex}` : `✓ Renk kodu kopyalandı: ${currentLoupeHex}`; + } + }); + } + + // ========================================== + // Squoosh Tarzı Dışa Aktarma & Sıkıştırma Stüdyosu + // ========================================== + let optFormat = "WEBP"; + let optQuality = 82; + let optDebounceTimer = null; + let optCurrentBlob = null; + + function openExportOptimizerModal() { + const modal = document.getElementById("exportOptimizerModal"); + if (!modal) return; + modal.style.display = "flex"; + const origSize = document.getElementById("optOrigSize"); + if (origSize && currentFile) { + origSize.textContent = formatBytes(currentFile.size); + } else if (origSize) { + origSize.textContent = "—"; + } + calcOptimizedPreview(); + } + + function closeExportOptimizerModal() { + const modal = document.getElementById("exportOptimizerModal"); + if (modal) modal.style.display = "none"; + } + + function handleExportOptBackdropClick(e) { + if (e.target.id === "exportOptimizerModal") closeExportOptimizerModal(); + } + + function setOptFormat(fmt) { + optFormat = fmt; + ["Webp", "Jpeg", "Png"].forEach(f => { + const b = document.getElementById("btnOptFmt" + f); + if (b) b.classList.toggle("active", f.toUpperCase() === fmt); + }); + const qRow = document.getElementById("rowOptQuality"); + if (qRow) qRow.style.display = (fmt === "PNG") ? "none" : "block"; + scheduleOptRecalc(); + } + + function updateOptQuality(val) { + optQuality = parseInt(val, 10); + const v = document.getElementById("valOptQuality"); + if (v) v.textContent = optQuality + "%"; + scheduleOptRecalc(); + } + + function scheduleOptRecalc() { + clearTimeout(optDebounceTimer); + optDebounceTimer = setTimeout(calcOptimizedPreview, 120); + } + + async function calcOptimizedPreview() { + const img = document.getElementById("imgAfter"); + if (!img || !img.src) return; + const statusText = document.getElementById("optStatusText"); + if (statusText) statusText.textContent = (currentLang === "en") ? "Compressing preview..." : "Sıkıştırma hesaplanıyor..."; + + const canvas = document.createElement("canvas"); + canvas.width = img.naturalWidth || img.width; + canvas.height = img.naturalHeight || img.height; + const ctx = canvas.getContext("2d"); + if (!ctx) return; + ctx.drawImage(img, 0, 0); + + const mime = optFormat === "WEBP" ? "image/webp" : (optFormat === "JPEG" ? "image/jpeg" : "image/png"); + const quality = optFormat === "PNG" ? undefined : (optQuality / 100); + + canvas.toBlob(blob => { + if (!blob) return; + optCurrentBlob = blob; + const newSizeEl = document.getElementById("optNewSize"); + const savingsEl = document.getElementById("optSavingsBadge"); + if (newSizeEl) newSizeEl.textContent = formatBytes(blob.size); + + const refSize = currentFile ? currentFile.size : (img.src.length * 0.75); + if (refSize > 0 && savingsEl) { + const ratio = Math.round(((refSize - blob.size) / refSize) * 100); + if (ratio >= 0) { + savingsEl.textContent = `-%${ratio} Kazanç`; + savingsEl.style.color = "#10b981"; + } else { + savingsEl.textContent = `+%${Math.abs(ratio)}`; + savingsEl.style.color = "#f59e0b"; + } + } + if (statusText) statusText.textContent = (currentLang === "en") ? "Optimization ready." : "Optimizasyon hazır."; + }, mime, quality); + } + + function downloadOptimizedImage() { + if (!optCurrentBlob) return; + const url = URL.createObjectURL(optCurrentBlob); + const a = document.createElement("a"); + a.href = url; + const ext = optFormat.toLowerCase(); + const baseName = (currentFile?.name || "pixelflow_export").replace(/\.[^/.]+$/, ""); + a.download = `${baseName}_optimized.${ext === "jpeg" ? "jpg" : ext}`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + closeExportOptimizerModal(); + statusMessage.textContent = (currentLang === "en") ? `✓ Optimized file downloaded (${formatBytes(optCurrentBlob.size)})` : `✓ Optimize dosya indirildi (${formatBytes(optCurrentBlob.size)})`; + } + window.addEventListener("keydown", (e) => { if ((e.ctrlKey || e.metaKey) && (e.key === "k" || e.key === "K")) { e.preventDefault(); @@ -5355,6 +5661,11 @@

openExportOptimizerModal() }, + { id: "loupe_inspector", group: "Görünüm & Renk", groupEn: "View & Color", name: "800% Piksel Büyüteci & Canlı Renk Pipeti", nameEn: "800% Pixel Loupe & Live Eyedropper", shortcut: "Z", action: () => toggleLoupe() }, { id: "exif_inspector", group: "Araçlar & Gizlilik", groupEn: "Tools & Privacy", name: "EXIF & Görsel Meta Verisi / Gizlilik Temizleyici", nameEn: "EXIF & Image Metadata Privacy Cleaner", shortcut: "Ctrl+I", action: () => openExifModal() }, // Belge & Evrak @@ -7576,6 +7894,7 @@

bytes: +def encode_image_bytes( + image: ImageArray, + image_format: str = "PNG", + quality: int | None = None, +) -> bytes: validate_image_array(image) fmt = image_format.upper() if fmt == "JPG": @@ -124,7 +128,10 @@ def encode_image_bytes(image: ImageArray, image_format: str = "PNG") -> bytes: raise InvalidImageError(f"Unsupported output image format: '{image_format}'") pil_img = _numpy_to_pil(image, target_format=fmt) buffer = BytesIO() - pil_img.save(buffer, format=fmt) + save_kwargs: dict[str, object] = {} + if quality is not None and fmt in ("JPEG", "WEBP"): + save_kwargs["quality"] = max(1, min(100, quality)) + pil_img.save(buffer, format=fmt, **save_kwargs) return buffer.getvalue() diff --git a/tests/test_api.py b/tests/test_api.py index c1bd2d3..e4127af 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -83,6 +83,15 @@ async def test_process_endpoint_success() -> None: assert pdf_resp.headers["content-type"] == "application/pdf" assert pdf_resp.content.startswith(b"%PDF") + jpeg_resp = await client.post( + "/v1/process", + files={"image": ("in.png", img_bytes, "image/png")}, + data={"pipeline": pipe_json, "output_format": "JPEG", "quality": "60"}, + ) + assert jpeg_resp.status_code == 200 + assert jpeg_resp.headers["content-type"] == "image/jpeg" + assert len(jpeg_resp.content) > 0 + @pytest.mark.anyio async def test_process_endpoint_limits() -> None: diff --git a/tests/test_core.py b/tests/test_core.py index 7edca4a..0d2f846 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -184,6 +184,15 @@ def test_io_modes_and_errors(tmp_path: Path) -> None: assert decode_image_bytes(encode_image_bytes(one_ch, "PNG")).shape == (8, 8) +def test_io_quality_compression() -> None: + img = np.random.randint(0, 255, (64, 64, 3), dtype=np.uint8) + high_q = encode_image_bytes(img, "JPEG", quality=95) + low_q = encode_image_bytes(img, "JPEG", quality=20) + assert len(high_q) > len(low_q) + webp_q = encode_image_bytes(img, "WEBP", quality=50) + assert len(webp_q) > 0 + + def test_io_edge_cases(tmp_path: Path) -> None: with pytest.raises(InvalidImageError): load_image(tmp_path / "nonexistent.png")