fix(image-manipulator): prevent excessive WebP compression and preserve crisp resolution with cwebp Sharp-YUV and quality controls
This commit is contained in:
@@ -1231,6 +1231,12 @@ function renderToolOptions() {
|
||||
<button class="seg-pill ${toolState.convert.format==='bmp'?'active':''}" onclick="setConvertFormat('bmp')">BMP</button>
|
||||
<button class="seg-pill ${toolState.convert.format==='tiff'?'active':''}" onclick="setConvertFormat('tiff')">TIFF</button>
|
||||
</div>
|
||||
<div class="ps-options-group" id="opt-convert-q-group" style="${(toolState.convert.format==='webp'||toolState.convert.format==='jpg'||toolState.convert.format==='avif')?'display:flex;align-items:center;':'display:none;'}">
|
||||
<span class="ps-options-label">Quality:</span>
|
||||
<input type="range" min="50" max="100" value="${toolState.convert.quality}" style="width: 110px;" oninput="updateConvertQuality(this.value)">
|
||||
<span class="label-val" id="opt-conv-val">${toolState.convert.quality}%</span>
|
||||
<span style="font-size: 10px; color: var(--accent-cyan); font-family: var(--font-mono); margin-left: 4px;">${toolState.convert.quality>=95?'(High Res)':toolState.convert.quality>=85?'(Balanced)':'' }</span>
|
||||
</div>
|
||||
`,
|
||||
compress: `
|
||||
<div class="ps-options-group">
|
||||
@@ -1465,10 +1471,10 @@ function renderToolControls() {
|
||||
<div class="ps-section-title">Transcode Format</div>
|
||||
<div class="input-group">
|
||||
<label>Target Extension</label>
|
||||
<select id="param-format" onchange="toolState.convert.format=this.value">
|
||||
<select id="param-format" onchange="toolState.convert.format=this.value; renderToolOptions();">
|
||||
<option value="png" ${toolState.convert.format==='png'?'selected':''}>PNG (Lossless)</option>
|
||||
<option value="jpg" ${toolState.convert.format==='jpg'?'selected':''}>JPG (Standard Web)</option>
|
||||
<option value="webp" ${toolState.convert.format==='webp'?'selected':''}>WEBP (High Efficiency)</option>
|
||||
<option value="webp" ${toolState.convert.format==='webp'?'selected':''}>WEBP (High Efficiency & Crisp)</option>
|
||||
<option value="avif" ${toolState.convert.format==='avif'?'selected':''}>AVIF (Modern Ultra-Compressed)</option>
|
||||
<option value="bmp" ${toolState.convert.format==='bmp'?'selected':''}>BMP (Windows Bitmap)</option>
|
||||
<option value="tiff" ${toolState.convert.format==='tiff'?'selected':''}>TIFF (Print Master)</option>
|
||||
@@ -1480,6 +1486,9 @@ function renderToolControls() {
|
||||
<label>Quality Profile (1-100) <span class="label-val" id="val-conv-q">${toolState.convert.quality}%</span></label>
|
||||
<input type="range" id="param-quality" min="1" max="100" value="${toolState.convert.quality}" oninput="updateConvertQuality(this.value)">
|
||||
</div>
|
||||
<div style="background: var(--bg-input); border: 1px solid var(--border-1); border-radius: var(--r-md); padding: 10px; font-size: 11px; color: var(--text-3); line-height: 1.4;">
|
||||
<i class="fa-solid fa-circle-check" style="color: var(--accent-emerald);"></i> <b>Crisp WebP Transcoding:</b> Powered by Google's native <code>cwebp</code> engine with Sharp-YUV color preservation. Retains full resolution and fine texture without blur (quality 92–98 recommended, 100 for lossless).
|
||||
</div>
|
||||
`,
|
||||
compress: `
|
||||
<div class="ps-section-title">Compression Engine</div>
|
||||
@@ -1487,7 +1496,7 @@ function renderToolControls() {
|
||||
<label>Output Format</label>
|
||||
<select id="param-format" onchange="updateCompressFormat(this.value)">
|
||||
<option value="original" ${toolState.compress.format==='original'?'selected':''}>Preserve Original Format</option>
|
||||
<option value="webp" ${toolState.compress.format==='webp'?'selected':''}>WEBP (Maximum Reduction)</option>
|
||||
<option value="webp" ${toolState.compress.format==='webp'?'selected':''}>WEBP (High Efficiency & Crisp)</option>
|
||||
<option value="jpg" ${toolState.compress.format==='jpg'?'selected':''}>JPG (Web Optimized)</option>
|
||||
<option value="png" ${toolState.compress.format==='png'?'selected':''}>PNG (Lossless Graphics)</option>
|
||||
</select>
|
||||
@@ -1731,6 +1740,10 @@ function updateConvertQuality(val) {
|
||||
toolState.convert.quality = q;
|
||||
const l = document.getElementById("val-conv-q");
|
||||
if (l) l.innerText = `${q}%`;
|
||||
const lOpt = document.getElementById("opt-conv-val");
|
||||
if (lOpt) lOpt.innerText = `${q}%`;
|
||||
const pQ = document.getElementById("param-quality");
|
||||
if (pQ && pQ.value != q) pQ.value = q;
|
||||
}
|
||||
window.updateConvertQuality = updateConvertQuality;
|
||||
|
||||
|
||||
@@ -138,16 +138,20 @@ func resizeHandler(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
func convertHandler(w http.ResponseWriter, r *http.Request) {
|
||||
if err := r.ParseMultipartForm(1024 * 1024 * 1024); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
targetFormat := strings.ToLower(r.FormValue("format"))
|
||||
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)
|
||||
return
|
||||
if quality <= 0 {
|
||||
quality = 95
|
||||
}
|
||||
|
||||
files := r.MultipartForm.File["images"]
|
||||
var results []SingleResult
|
||||
for _, fileHeader := range files {
|
||||
@@ -186,14 +190,18 @@ 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)
|
||||
return
|
||||
}
|
||||
|
||||
quality := parseFormInt(r, "quality", 85)
|
||||
if quality <= 0 {
|
||||
quality = 85
|
||||
}
|
||||
targetFormat := strings.ToLower(r.FormValue("format"))
|
||||
targetSizeMB := parseFormFloat(r, "target_size_mb", 0)
|
||||
|
||||
files := r.MultipartForm.File["images"]
|
||||
var results []SingleResult
|
||||
for _, fileHeader := range files {
|
||||
@@ -287,7 +295,10 @@ func simulateCompressionHandler(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
quality := parseFormInt(r, "quality", 80)
|
||||
quality := parseFormInt(r, "quality", 85)
|
||||
if quality <= 0 {
|
||||
quality = 85
|
||||
}
|
||||
targetFormat := strings.ToLower(r.FormValue("format"))
|
||||
|
||||
img, format, err := image.Decode(file)
|
||||
|
||||
@@ -318,13 +318,19 @@ func processSingleBatchFile(file string, operation string, params map[string]int
|
||||
case "convert":
|
||||
targetFmt := getParamString(params, "format", "png")
|
||||
quality := getParamInt(params, "quality", 95)
|
||||
if quality <= 0 {
|
||||
quality = 95
|
||||
}
|
||||
buf, finalFmt = compressLogic(img, targetFmt, quality)
|
||||
case "compress":
|
||||
targetFmt := getParamString(params, "format", "original")
|
||||
if targetFmt == "original" {
|
||||
targetFmt = format
|
||||
}
|
||||
q := getParamInt(params, "quality", 80)
|
||||
q := getParamInt(params, "quality", 85)
|
||||
if q <= 0 {
|
||||
q = 85
|
||||
}
|
||||
targetMB := getParamFloat(params, "target_size_mb", 0)
|
||||
currentMB := getParamFloat(params, "current_size_mb", 0)
|
||||
if targetMB > 0 && currentMB > targetMB {
|
||||
|
||||
@@ -341,13 +341,108 @@ func hasTransparency(img image.Image) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// encodeWebP encodes an image to high-fidelity WebP without aggressive compression or resolution loss.
|
||||
func encodeWebP(img image.Image, quality int) ([]byte, error) {
|
||||
if quality <= 0 {
|
||||
quality = 95
|
||||
}
|
||||
if quality > 100 {
|
||||
quality = 100
|
||||
}
|
||||
|
||||
var pngBuf bytes.Buffer
|
||||
if err := png.Encode(&pngBuf, img); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rawPng := pngBuf.Bytes()
|
||||
|
||||
// 1. First-class: Google cwebp binary with Sharp-YUV and full alpha quality
|
||||
if cwebpPath, err := exec.LookPath("cwebp"); err == nil && cwebpPath != "" {
|
||||
var args []string
|
||||
if quality >= 100 {
|
||||
// True lossless WebP compression
|
||||
args = []string{"-lossless", "-m", "6", "-exact", "-o", "-", "--", "-"}
|
||||
} else {
|
||||
// High quality lossy: minimal quantization, Sharp-YUV prevents color edge blur, exact alpha
|
||||
args = []string{
|
||||
"-q", strconv.Itoa(quality),
|
||||
"-m", "6",
|
||||
"-sharp_yuv",
|
||||
"-alpha_q", "100",
|
||||
"-exact",
|
||||
"-o", "-",
|
||||
"--", "-",
|
||||
}
|
||||
}
|
||||
|
||||
cmd := exec.Command(cwebpPath, args...)
|
||||
cmd.Stdin = bytes.NewReader(rawPng)
|
||||
var outBuf bytes.Buffer
|
||||
cmd.Stdout = &outBuf
|
||||
if err := cmd.Run(); err == nil && outBuf.Len() > 0 {
|
||||
return outBuf.Bytes(), nil
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Fallback to Python Pillow in user venv (properly supports libwebp quality, method 6, alpha)
|
||||
pythonBin := "/home/creserver/extras/local_venv/bin/python3"
|
||||
if _, err := os.Stat(pythonBin); os.IsNotExist(err) {
|
||||
pythonBin = "python3"
|
||||
}
|
||||
|
||||
pyScript := fmt.Sprintf(`import sys, io
|
||||
from PIL import Image
|
||||
data = sys.stdin.buffer.read()
|
||||
img = Image.open(io.BytesIO(data))
|
||||
if img.mode == 'CMYK':
|
||||
img = img.convert('RGB')
|
||||
elif img.mode in ('P', 'LA'):
|
||||
img = img.convert('RGBA')
|
||||
|
||||
out = io.BytesIO()
|
||||
q = %d
|
||||
if q >= 100:
|
||||
img.save(out, format='WEBP', lossless=True, method=6)
|
||||
else:
|
||||
img.save(out, format='WEBP', quality=q, method=6, alpha_quality=100)
|
||||
sys.stdout.buffer.write(out.getvalue())
|
||||
`, quality)
|
||||
|
||||
pyCmd := exec.Command(pythonBin, "-c", pyScript)
|
||||
pyCmd.Stdin = bytes.NewReader(rawPng)
|
||||
var pyOutBuf bytes.Buffer
|
||||
pyCmd.Stdout = &pyOutBuf
|
||||
if err := pyCmd.Run(); err == nil && pyOutBuf.Len() > 0 {
|
||||
return pyOutBuf.Bytes(), nil
|
||||
}
|
||||
|
||||
// 3. Fallback to ImageMagick if neither cwebp nor Pillow are available
|
||||
imQuality := quality
|
||||
if imQuality <= 0 {
|
||||
imQuality = 95
|
||||
}
|
||||
imCmd := exec.Command("convert", "-", "-quality", strconv.Itoa(imQuality), "webp:-")
|
||||
imCmd.Stdin = bytes.NewReader(rawPng)
|
||||
var imOutBuf bytes.Buffer
|
||||
imCmd.Stdout = &imOutBuf
|
||||
if err := imCmd.Run(); err == nil && imOutBuf.Len() > 0 {
|
||||
return imOutBuf.Bytes(), nil
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("failed to encode webp")
|
||||
}
|
||||
|
||||
func encodeExternal(img image.Image, targetFormat string, quality int) ([]byte, error) {
|
||||
fmtLower := strings.ToLower(targetFormat)
|
||||
if fmtLower == "webp" {
|
||||
return encodeWebP(img, quality)
|
||||
}
|
||||
|
||||
var pngBuf bytes.Buffer
|
||||
if err := png.Encode(&pngBuf, img); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
fmtLower := strings.ToLower(targetFormat)
|
||||
if fmtLower == "jpeg" {
|
||||
fmtLower = "jpg"
|
||||
}
|
||||
@@ -427,6 +522,10 @@ func compressLogic(img image.Image, targetFormat string, quality int) ([]byte, s
|
||||
if err := png.Encode(&buf, img); err == nil {
|
||||
return buf.Bytes(), "PNG"
|
||||
}
|
||||
case "WEBP":
|
||||
if data, err := encodeWebP(img, quality); err == nil {
|
||||
return data, "WEBP"
|
||||
}
|
||||
case "BMP":
|
||||
if err := bmp.Encode(&buf, img); err == nil {
|
||||
return buf.Bytes(), "BMP"
|
||||
@@ -440,7 +539,7 @@ func compressLogic(img image.Image, targetFormat string, quality int) ([]byte, s
|
||||
return buf.Bytes(), "GIF"
|
||||
}
|
||||
default:
|
||||
// WEBP, ICO, AVIF, HEIC, etc.
|
||||
// ICO, AVIF, HEIC, etc.
|
||||
if data, err := encodeExternal(img, targetFmt, quality); err == nil {
|
||||
return data, targetFmt
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user