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

572 lines
15 KiB
Go

package main
import (
"archive/zip"
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"image"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"net/http"
"path/filepath"
"strconv"
"strings"
_ "golang.org/x/image/bmp"
_ "golang.org/x/image/tiff"
_ "golang.org/x/image/webp"
)
func imageToBase64(img image.Image, format string) (string, string) {
buf, fmtTarget := compressLogic(img, format, 95)
b64 := base64.StdEncoding.EncodeToString(buf)
return fmtTarget, b64
}
func getImageInfo(img image.Image, format string) map[string]interface{} {
bounds := img.Bounds()
return map[string]interface{}{
"width": bounds.Dx(),
"height": bounds.Dy(),
"format": format,
"mode": "RGB", // Go's image interfaces abstract this mostly
}
}
type SingleResult struct {
Success bool `json:"success"`
Filename string `json:"filename"`
Image string `json:"image"`
Data string `json:"data,omitempty"`
Info map[string]interface{} `json:"info"`
CompressedSizeKB float64 `json:"compressed_size_kb,omitempty"`
}
type BatchResult struct {
Results []SingleResult `json:"results"`
}
func parseFormFloat(r *http.Request, key string, def float64) float64 {
val := r.FormValue(key)
if val == "" {
return def
}
f, err := strconv.ParseFloat(val, 64)
if err != nil {
return def
}
return f
}
func parseFormInt(r *http.Request, key string, def int) int {
val := r.FormValue(key)
if val == "" {
return def
}
i, err := strconv.Atoi(val)
if err != nil {
return def
}
return i
}
func handleProcessing(w http.ResponseWriter, r *http.Request, processFunc func(image.Image, string, int, string) (image.Image, string, float64)) {
if err := r.ParseMultipartForm(1024 * 1024 * 1024); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
files := r.MultipartForm.File["images"]
var results []SingleResult
for i, fileHeader := range files {
file, err := fileHeader.Open()
if err != nil {
continue
}
defer file.Close()
img, format, err := image.Decode(file)
if err != nil {
continue
}
if format == "" {
format = "PNG"
}
processedImg, finalFormat, compressedSizeKB := processFunc(img, format, i, fileHeader.Filename)
if processedImg == nil {
continue
}
finalFmt, b64 := imageToBase64(processedImg, finalFormat)
dataURI := fmt.Sprintf("data:image/%s;base64,%s", strings.ToLower(finalFmt), b64)
res := SingleResult{
Success: true,
Filename: fileHeader.Filename,
Image: dataURI,
Data: dataURI,
Info: getImageInfo(processedImg, finalFmt),
}
if compressedSizeKB > 0 {
res.CompressedSizeKB = compressedSizeKB
}
results = append(results, res)
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(BatchResult{Results: results})
}
func resizeHandler(w http.ResponseWriter, r *http.Request) {
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) {
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
})
}
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 quality <= 0 {
quality = 95
}
files := r.MultipartForm.File["images"]
var results []SingleResult
for _, fileHeader := range files {
file, _ := fileHeader.Open()
img, format, err := image.Decode(file)
file.Close()
if err != nil {
continue
}
if format == "" {
format = "png"
}
buf, finalFmt := compressLogic(img, targetFormat, quality)
b64 := base64.StdEncoding.EncodeToString(buf)
ext := strings.ToLower(finalFmt)
if ext == "jpeg" {
ext = "jpg"
}
newFilename := strings.TrimSuffix(fileHeader.Filename, filepath.Ext(fileHeader.Filename)) + "." + ext
mimeType := strings.ToLower(finalFmt)
if mimeType == "jpg" {
mimeType = "jpeg"
}
dataURI := fmt.Sprintf("data:image/%s;base64,%s", mimeType, b64)
results = append(results, SingleResult{
Success: true,
Filename: newFilename,
Image: dataURI,
Data: dataURI,
Info: getImageInfo(img, finalFmt),
})
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(BatchResult{Results: results})
}
func compressHandler(w http.ResponseWriter, r *http.Request) {
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 {
file, _ := fileHeader.Open()
img, format, err := image.Decode(file)
file.Close()
if err != nil {
continue
}
fmtTarget := targetFormat
if fmtTarget == "original" || fmtTarget == "" {
fmtTarget = format
}
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
ext := strings.ToLower(finalFmt)
if ext == "jpeg" {
ext = "jpg"
}
newFilename := strings.TrimSuffix(fileHeader.Filename, filepath.Ext(fileHeader.Filename)) + "." + ext
mimeType := strings.ToLower(finalFmt)
if mimeType == "jpg" {
mimeType = "jpeg"
}
dataURI := fmt.Sprintf("data:image/%s;base64,%s", mimeType, b64)
results = append(results, SingleResult{
Success: true,
Filename: newFilename,
Image: dataURI,
Data: dataURI,
Info: getImageInfo(img, finalFmt),
CompressedSizeKB: sizeKB,
})
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(BatchResult{Results: results})
}
func simulateCompressionHandler(w http.ResponseWriter, r *http.Request) {
if err := r.ParseMultipartForm(1024 * 1024 * 1024); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
file, fileHeader, err := r.FormFile("image")
if err != nil {
file, fileHeader, err = r.FormFile("images")
}
if err != nil {
http.Error(w, "No file", http.StatusBadRequest)
return
}
defer file.Close()
quality := parseFormInt(r, "quality", 85)
if quality <= 0 {
quality = 85
}
targetFormat := strings.ToLower(r.FormValue("format"))
img, format, err := image.Decode(file)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
origSize := fileHeader.Size
fmtTarget := targetFormat
if fmtTarget == "original" || fmtTarget == "" {
fmtTarget = format
}
buf, _ := compressLogic(img, fmtTarget, quality)
newSize := int64(len(buf))
reduction := 0.0
if origSize > 0 {
reduction = (1.0 - float64(newSize)/float64(origSize)) * 100.0
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"original_size": origSize,
"new_size": newSize,
"reduction": reduction,
})
}
func cropHandler(w http.ResponseWriter, r *http.Request) {
left := parseFormInt(r, "left", 0)
top := parseFormInt(r, "top", 0)
right := parseFormInt(r, "right", 800)
bottom := parseFormInt(r, "bottom", 600)
leftPct := parseFormFloat(r, "left_pct", -1)
topPct := parseFormFloat(r, "top_pct", -1)
rightPct := parseFormFloat(r, "right_pct", -1)
bottomPct := parseFormFloat(r, "bottom_pct", -1)
handleProcessing(w, r, func(img image.Image, format string, idx int, filename string) (image.Image, string, float64) {
bounds := img.Bounds()
l, t, rVal, b := left, top, right, bottom
if leftPct >= 0 && rightPct > leftPct && topPct >= 0 && bottomPct > topPct {
wDx := float64(bounds.Dx())
hDy := float64(bounds.Dy())
l = int(wDx * leftPct / 100.0)
rVal = int(wDx * rightPct / 100.0)
t = int(hDy * topPct / 100.0)
b = int(hDy * bottomPct / 100.0)
}
return cropImage(img, l, t, rVal, b), format, 0
})
}
func filterHandler(w http.ResponseWriter, r *http.Request) {
filterType := r.FormValue("filter")
if filterType == "" {
filterType = r.FormValue("filter_type")
}
if filterType == "" {
filterType = "BLUR"
}
handleProcessing(w, r, func(img image.Image, format string, idx int, filename string) (image.Image, string, float64) {
return filterImage(img, filterType), format, 0
})
}
func rotateHandler(w http.ResponseWriter, r *http.Request) {
op := r.FormValue("operation")
if op == "" {
op = "90"
}
handleProcessing(w, r, func(img image.Image, format string, idx int, filename string) (image.Image, string, float64) {
return rotateImage(img, op), format, 0
})
}
func watermarkHandler(w http.ResponseWriter, r *http.Request) {
if err := r.ParseMultipartForm(1024 * 1024 * 1024); err != nil {
http.Error(w, err.Error(), 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))
}
}
if wmImg == nil {
http.Error(w, "No watermark image provided", http.StatusBadRequest)
return
}
position := r.FormValue("position")
if position == "" {
position = "bottom_right"
}
opacity := parseFormInt(r, "opacity", 60)
files := r.MultipartForm.File["images"]
var results []SingleResult
for _, fileHeader := range files {
file, _ := fileHeader.Open()
img, _, err := image.Decode(file)
file.Close()
if err != nil {
continue
}
processed := watermarkImage(img, wmImg, position, opacity)
finalFmt, b64 := imageToBase64(processed, "PNG")
dataURI := fmt.Sprintf("data:image/%s;base64,%s", strings.ToLower(finalFmt), b64)
results = append(results, SingleResult{
Success: true,
Filename: fileHeader.Filename,
Image: dataURI,
Data: dataURI,
Info: getImageInfo(processed, "PNG"),
})
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(BatchResult{Results: results})
}
func maskHandler(w http.ResponseWriter, r *http.Request) {
if err := r.ParseMultipartForm(1024 * 1024 * 1024); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
files := r.MultipartForm.File["images"]
var results []SingleResult
for _, fileHeader := range files {
file, _ := fileHeader.Open()
img, format, err := image.Decode(file)
file.Close()
if err != nil {
continue
}
finalFmt, b64 := imageToBase64(img, "PNG")
dataURI := fmt.Sprintf("data:image/%s;base64,%s", strings.ToLower(finalFmt), b64)
results = append(results, SingleResult{
Success: true,
Filename: "mask_output.png",
Image: dataURI,
Data: dataURI,
Info: getImageInfo(img, format),
})
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(BatchResult{Results: results})
}
func downloadAllHandler(w http.ResponseWriter, r *http.Request) {
var body struct {
Images []struct {
Filename string `json:"filename"`
Name string `json:"name"`
Image string `json:"image"`
Data string `json:"data"`
} `json:"images"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if len(body.Images) == 0 {
http.Error(w, "No images provided", http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/zip")
w.Header().Set("Content-Disposition", "attachment; filename=processed_images.zip")
archive := zip.NewWriter(w)
defer archive.Close()
for i, imgData := range body.Images {
filename := imgData.Filename
if filename == "" {
filename = imgData.Name
}
if filename == "" {
filename = fmt.Sprintf("image_%d.png", i)
}
b64Str := imgData.Image
if b64Str == "" {
b64Str = imgData.Data
}
if idx := strings.Index(b64Str, ","); idx != -1 {
b64Str = b64Str[idx+1:]
}
imageBytes, err := base64.StdEncoding.DecodeString(b64Str)
if err != nil {
continue
}
writer, err := archive.Create(filename)
if err != nil {
continue
}
writer.Write(imageBytes)
}
}
func adjustHandler(w http.ResponseWriter, r *http.Request) {
brightness := parseFormFloat(r, "brightness", 0)
contrast := parseFormFloat(r, "contrast", 0)
saturation := parseFormFloat(r, "saturation", 0)
gamma := parseFormFloat(r, "gamma", 1.0)
handleProcessing(w, r, func(img image.Image, format string, idx int, filename string) (image.Image, string, float64) {
return adjustColor(img, brightness, contrast, saturation, gamma), format, 0
})
}
func borderHandler(w http.ResponseWriter, r *http.Request) {
borderWidth := parseFormInt(r, "border_width", 20)
borderColor := r.FormValue("border_color")
if borderColor == "" {
borderColor = "#ffffff"
}
padAspect := r.FormValue("pad_aspect")
handleProcessing(w, r, func(img image.Image, format string, idx int, filename string) (image.Image, string, float64) {
return addBorderCanvas(img, borderWidth, borderColor, padAspect), format, 0
})
}
func roundCornersHandler(w http.ResponseWriter, r *http.Request) {
radius := parseFormInt(r, "radius", 30)
isCircle := r.FormValue("is_circle") == "true"
handleProcessing(w, r, func(img image.Image, format string, idx int, filename string) (image.Image, string, float64) {
return roundCorners(img, radius, isCircle), "PNG", 0
})
}
func stripMetadataHandler(w http.ResponseWriter, r *http.Request) {
quality := parseFormInt(r, "quality", 95)
targetFormat := strings.ToLower(r.FormValue("format"))
handleProcessing(w, r, func(img image.Image, format string, idx int, filename string) (image.Image, string, float64) {
fmtTarget := targetFormat
if fmtTarget == "" || fmtTarget == "original" {
fmtTarget = format
}
buf, finalFmt := compressLogic(img, fmtTarget, quality)
sizeKB := float64(len(buf)) / 1024.0
cleanImg, _, _ := image.Decode(bytes.NewReader(buf))
if cleanImg == nil {
cleanImg = img
}
return cleanImg, finalFmt, sizeKB
})
}