Files
Unified_Dashboard_Suite_Go/cmd/image-manipulator/processor.go
T

463 lines
12 KiB
Go

package main
import (
"bytes"
"fmt"
"image"
"image/color"
"image/draw"
"image/gif"
"image/jpeg"
"image/png"
"math"
"os"
"os/exec"
"strconv"
"strings"
"github.com/disintegration/imaging"
"golang.org/x/image/bmp"
"golang.org/x/image/tiff"
)
// 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.Fit(img, width, height, imaging.Lanczos)
}
if width > 0 && height <= 0 {
return imaging.Resize(img, width, 0, imaging.Lanczos)
}
if height > 0 && width <= 0 {
return imaging.Resize(img, 0, height, imaging.Lanczos)
}
return img
}
targetW := width
if targetW <= 0 {
targetW = img.Bounds().Dx()
}
targetH := height
if targetH <= 0 {
targetH = img.Bounds().Dy()
}
return imaging.Resize(img, targetW, targetH, imaging.Lanczos)
}
func filterImage(img image.Image, filterType string) image.Image {
switch strings.ToUpper(filterType) {
case "BLUR":
return imaging.Blur(img, 2.5)
case "SHARPEN":
return imaging.Sharpen(img, 2.0)
case "GRAYSCALE":
return imaging.Grayscale(img)
case "INVERT":
return imaging.Invert(img)
case "SEPIA":
gray := imaging.Grayscale(img)
return imaging.AdjustSaturation(imaging.AdjustSigmoid(gray, 0.5, 3.0), 50)
case "EMBOSS":
kernel := [9]float64{
-2, -1, 0,
-1, 1, 1,
0, 1, 2,
}
return imaging.Convolve3x3(img, kernel, nil)
case "CONTOUR", "EDGE_ENHANCE":
kernel := [9]float64{
-1, -1, -1,
-1, 8, -1,
-1, -1, -1,
}
return imaging.Convolve3x3(img, kernel, nil)
case "WARM":
return imaging.AdjustFunc(img, func(c color.NRGBA) color.NRGBA {
r := int(c.R) + 25
b := int(c.B) - 15
if r > 255 { r = 255 }
if b < 0 { b = 0 }
return color.NRGBA{R: uint8(r), G: c.G, B: uint8(b), A: c.A}
})
case "COOL":
return imaging.AdjustFunc(img, func(c color.NRGBA) color.NRGBA {
r := int(c.R) - 15
b := int(c.B) + 30
if r < 0 { r = 0 }
if b > 255 { b = 255 }
return color.NRGBA{R: uint8(r), G: c.G, B: uint8(b), A: c.A}
})
case "VINTAGE":
sepia := imaging.AdjustSaturation(imaging.AdjustSigmoid(imaging.Grayscale(img), 0.5, 2.5), 35)
return imaging.AdjustContrast(sepia, 15)
default:
return img
}
}
func parseHexColor(hexStr string) color.NRGBA {
hexStr = strings.TrimPrefix(strings.TrimSpace(hexStr), "#")
if len(hexStr) == 3 {
hexStr = string([]byte{hexStr[0], hexStr[0], hexStr[1], hexStr[1], hexStr[2], hexStr[2]})
}
if len(hexStr) == 6 {
val, err := strconv.ParseUint(hexStr, 16, 32)
if err == nil {
return color.NRGBA{
R: uint8(val >> 16),
G: uint8((val >> 8) & 0xFF),
B: uint8(val & 0xFF),
A: 255,
}
}
} else if len(hexStr) == 8 {
val, err := strconv.ParseUint(hexStr, 16, 32)
if err == nil {
return color.NRGBA{
R: uint8(val >> 24),
G: uint8((val >> 16) & 0xFF),
B: uint8((val >> 8) & 0xFF),
A: uint8(val & 0xFF),
}
}
}
return color.NRGBA{0, 0, 0, 255}
}
func adjustColor(img image.Image, brightness, contrast, saturation, gamma float64) image.Image {
res := img
if brightness != 0 {
res = imaging.AdjustBrightness(res, brightness)
}
if contrast != 0 {
res = imaging.AdjustContrast(res, contrast)
}
if saturation != 0 {
res = imaging.AdjustSaturation(res, saturation)
}
if gamma > 0 && gamma != 1.0 {
res = imaging.AdjustGamma(res, gamma)
}
return res
}
func roundCorners(img image.Image, radius int, isCircle bool) image.Image {
bounds := img.Bounds()
w, h := bounds.Dx(), bounds.Dy()
if isCircle {
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
}
dst := image.NewNRGBA(image.Rect(0, 0, w, h))
rSq := float64(radius * radius)
innerRSq := float64((radius - 1) * (radius - 1))
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
c := color.NRGBAModel.Convert(img.At(bounds.Min.X+x, bounds.Min.Y+y)).(color.NRGBA)
var dx, dy float64
inCorner := false
if x < radius && y < radius {
dx, dy = float64(radius-x), float64(radius-y)
inCorner = true
} else if x >= w-radius && y < radius {
dx, dy = float64(x-(w-radius-1)), float64(radius-y)
inCorner = true
} else if x < radius && y >= h-radius {
dx, dy = float64(radius-x), float64(y-(h-radius-1))
inCorner = true
} else if x >= w-radius && y >= h-radius {
dx, dy = float64(x-(w-radius-1)), float64(y-(h-radius-1))
inCorner = true
}
if inCorner {
distSq := dx*dx + dy*dy
if distSq > rSq {
c.A = 0
} else if distSq > innerRSq {
dist := math.Sqrt(distSq)
factor := float64(radius) - dist
if factor < 0 {
factor = 0
} else if factor > 1 {
factor = 1
}
c.A = uint8(float64(c.A) * factor)
}
}
dst.SetNRGBA(x, y, c)
}
}
return dst
}
func addBorderCanvas(img image.Image, borderWidth int, borderColorHex string, padAspect string) image.Image {
bounds := img.Bounds()
w, h := bounds.Dx(), bounds.Dy()
borderColor := parseHexColor(borderColorHex)
newW := w + borderWidth*2
newH := h + borderWidth*2
if padAspect != "" && padAspect != "none" {
var targetRatio float64
switch padAspect {
case "1:1":
targetRatio = 1.0
case "16:9":
targetRatio = 16.0 / 9.0
case "9:16":
targetRatio = 9.0 / 16.0
case "4:5":
targetRatio = 4.0 / 5.0
case "4:3":
targetRatio = 4.0 / 3.0
}
if targetRatio > 0 {
curRatio := float64(newW) / float64(newH)
if curRatio < targetRatio {
newW = int(float64(newH) * targetRatio)
} else if curRatio > targetRatio {
newH = int(float64(newW) / targetRatio)
}
}
}
canvas := imaging.New(newW, newH, borderColor)
posX := (newW - w) / 2
posY := (newH - h) / 2
return imaging.Paste(canvas, img, image.Pt(posX, posY))
}
func rotateImage(img image.Image, op string) image.Image {
switch op {
case "90":
return imaging.Rotate270(img) // Clockwise 90
case "180":
return imaging.Rotate180(img)
case "270":
return imaging.Rotate90(img) // Clockwise 270
case "FLIP_H":
return imaging.FlipH(img)
case "FLIP_V":
return imaging.FlipV(img)
default:
if angle, err := strconv.ParseFloat(op, 64); err == nil {
return imaging.Rotate(img, -angle, color.Transparent)
}
return img
}
}
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 > w {
right = w
}
if bottom > h {
bottom = h
}
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)
}
func watermarkImage(baseImg, watermarkImg image.Image, position string, opacity int) image.Image {
baseBounds := baseImg.Bounds()
wmWidth := baseBounds.Dx() / 4
if wmWidth == 0 {
wmWidth = 1
}
wmBounds := watermarkImg.Bounds()
wmHeight := int(float64(wmBounds.Dy()) * (float64(wmWidth) / float64(wmBounds.Dx())))
if wmHeight == 0 {
wmHeight = 1
}
wmResized := imaging.Resize(watermarkImg, wmWidth, wmHeight, imaging.Lanczos)
// Apply opacity
mask := image.NewUniform(color.Alpha{uint8(255 * opacity / 100)})
wmWithOpacity := image.NewRGBA(wmResized.Bounds())
draw.DrawMask(wmWithOpacity, wmWithOpacity.Bounds(), wmResized, image.Point{}, mask, image.Point{}, draw.Over)
var pt image.Point
switch position {
case "top_left":
pt = image.Pt(10, 10)
case "top_right":
pt = image.Pt(baseBounds.Dx()-wmWidth-10, 10)
case "bottom_left":
pt = image.Pt(10, baseBounds.Dy()-wmHeight-10)
case "bottom_right":
pt = image.Pt(baseBounds.Dx()-wmWidth-10, baseBounds.Dy()-wmHeight-10)
default: // center
pt = image.Pt((baseBounds.Dx()-wmWidth)/2, (baseBounds.Dy()-wmHeight)/2)
}
result := image.NewRGBA(baseBounds)
draw.Draw(result, baseBounds, baseImg, image.Point{}, draw.Src)
draw.Draw(result, wmWithOpacity.Bounds().Add(pt), wmWithOpacity, image.Point{}, draw.Over)
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 {
return nil, err
}
fmtLower := strings.ToLower(targetFormat)
if fmtLower == "jpeg" {
fmtLower = "jpg"
}
// 1. Try ImageMagick convert: convert - -quality <quality> <fmt>:-
cmd := exec.Command("convert", "-", "-quality", strconv.Itoa(quality), fmtLower+":-")
cmd.Stdin = bytes.NewReader(pngBuf.Bytes())
var outBuf bytes.Buffer
cmd.Stdout = &outBuf
if err := cmd.Run(); err == nil && outBuf.Len() > 0 {
return outBuf.Bytes(), nil
}
// 2. Fallback to Python PIL in user's venv
pythonBin := "/home/creserver/extras/local_venv/bin/python3"
if _, err := os.Stat(pythonBin); os.IsNotExist(err) {
pythonBin = "python3"
}
pilFormat := strings.ToUpper(targetFormat)
if pilFormat == "JPG" {
pilFormat = "JPEG"
}
pyScript := fmt.Sprintf(`import sys, io
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=fmt, quality=%d)
sys.stdout.buffer.write(out.getvalue())
`, pilFormat, quality)
pyCmd := exec.Command(pythonBin, "-c", pyScript)
pyCmd.Stdin = bytes.NewReader(pngBuf.Bytes())
var pyOutBuf bytes.Buffer
pyCmd.Stdout = &pyOutBuf
if err := pyCmd.Run(); err == nil && pyOutBuf.Len() > 0 {
return pyOutBuf.Bytes(), nil
}
return nil, fmt.Errorf("external encoder failed for %s", targetFormat)
}
func compressLogic(img image.Image, targetFormat string, quality int) ([]byte, string) {
targetFmt := strings.ToUpper(strings.TrimSpace(targetFormat))
if targetFmt == "JPG" {
targetFmt = "JPEG"
}
if targetFmt == "" {
targetFmt = "PNG"
}
var buf bytes.Buffer
switch targetFmt {
case "JPEG":
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":
if err := png.Encode(&buf, img); err == nil {
return buf.Bytes(), "PNG"
}
case "BMP":
if err := bmp.Encode(&buf, img); err == nil {
return buf.Bytes(), "BMP"
}
case "TIFF":
if err := tiff.Encode(&buf, img, nil); err == nil {
return buf.Bytes(), "TIFF"
}
case "GIF":
if err := gif.Encode(&buf, img, nil); err == nil {
return buf.Bytes(), "GIF"
}
default:
// WEBP, ICO, AVIF, HEIC, etc.
if data, err := encodeExternal(img, targetFmt, quality); err == nil {
return data, targetFmt
}
}
// If switch didn't return (e.g. BMP/TIFF native error, or unknown), try external
if data, err := encodeExternal(img, targetFmt, quality); err == nil {
return data, targetFmt
}
// Ultimate fallback to PNG or JPEG
buf.Reset()
if err := png.Encode(&buf, img); err == nil {
return buf.Bytes(), "PNG"
}
buf.Reset()
jpeg.Encode(&buf, img, &jpeg.Options{Quality: quality})
return buf.Bytes(), "JPEG"
}