433 lines
11 KiB
Go
433 lines
11 KiB
Go
package main
|
|
|
|
import (
|
|
"archive/zip"
|
|
"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 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", 800)
|
|
height := parseFormInt(r, "height", 600)
|
|
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
|
|
})
|
|
}
|
|
|
|
func convertHandler(w http.ResponseWriter, r *http.Request) {
|
|
targetFormat := strings.ToLower(r.FormValue("format"))
|
|
if targetFormat == "" {
|
|
targetFormat = "png"
|
|
}
|
|
|
|
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
|
|
}
|
|
if format == "" {
|
|
format = "png"
|
|
}
|
|
|
|
finalFmt, b64 := imageToBase64(img, targetFormat)
|
|
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) {
|
|
quality := parseFormInt(r, "quality", 80)
|
|
targetFormat := strings.ToLower(r.FormValue("format"))
|
|
|
|
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
|
|
}
|
|
|
|
fmtTarget := targetFormat
|
|
if fmtTarget == "original" || fmtTarget == "" {
|
|
fmtTarget = format
|
|
}
|
|
|
|
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", 80)
|
|
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)
|
|
|
|
handleProcessing(w, r, func(img image.Image, format string, idx int, filename string) (image.Image, string, float64) {
|
|
return cropImage(img, left, top, right, bottom), 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
|
|
}
|
|
|
|
wmFile, _, err := r.FormFile("watermark")
|
|
if err != nil {
|
|
http.Error(w, "No watermark image provided", http.StatusBadRequest)
|
|
return
|
|
}
|
|
defer wmFile.Close()
|
|
wmImg, _, err := image.Decode(wmFile)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
position := r.FormValue("position")
|
|
if position == "" {
|
|
position = "bottom_right"
|
|
}
|
|
opacity := parseFormInt(r, "opacity", 50)
|
|
|
|
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)
|
|
}
|
|
}
|