Files
mtusi2026lab6/service/internal/pkg/imageprocessor/image.go
T
2026-11-17 13:08:13 +03:00

84 lines
2.3 KiB
Go

package imageprocessor
import (
"context"
"fmt"
"image"
_ "image/jpeg"
_ "image/png"
"os"
"os/exec"
"path/filepath"
"time"
)
func run(ctx context.Context, args ...string) error {
cmd := exec.CommandContext(ctx, "magick", args...)
cmd.Env = append(os.Environ(), "MAGICK_MEMORY_LIMIT=256MiB", "MAGICK_MAP_LIMIT=0", "MAGICK_DISK_LIMIT=256MiB", "MAGICK_THREAD_LIMIT=1", "MAGICK_TIME_LIMIT=60")
cmd.WaitDelay = time.Second
if err := cmd.Run(); err != nil {
if ctx.Err() != nil {
return ctx.Err()
}
return fmt.Errorf("image conversion failed: %w", err)
}
return nil
}
func Validate(ctx context.Context, path string) error {
return run(ctx, "-regard-warnings", path, "null:")
}
type Result struct {
Name, Path, MIME string
Width, Height int
}
func fit(w, h, limit int) (int, int) {
if w <= limit && h <= limit {
return w, h
}
if w >= h {
return limit, max(1, h*limit/w)
}
return max(1, w*limit/h), limit
}
func Process(ctx context.Context, source, dir string, version int) ([]Result, error) {
normalized := filepath.Join(dir, "normalized.png")
if e := run(ctx, source, "-auto-orient", "-background", "white", "-alpha", "remove", "-alpha", "off", "-strip", "png:"+normalized); e != nil {
return nil, e
}
f, e := os.Open(normalized)
if e != nil {
return nil, e
}
cfg, _, e := image.DecodeConfig(f)
f.Close()
if e != nil {
return nil, e
}
tw, th := fit(cfg.Width, cfg.Height, 256)
ow, oh := fit(cfg.Width, cfg.Height, 1280)
out := []Result{{"thumbnail", filepath.Join(dir, "thumbnail.jpg"), "image/jpeg", tw, th}, {"crop", filepath.Join(dir, "crop.jpg"), "image/jpeg", 128, 128}, {"optimized", filepath.Join(dir, "optimized.webp"), "image/webp", ow, oh}}
for _, v := range out {
args := []string{normalized}
if v.Name == "crop" {
side := min(cfg.Width, cfg.Height)
args = append(args, "-gravity", "center", "-crop", fmt.Sprintf("%dx%d+0+0", side, side), "+repage")
}
args = append(args, "-resize", fmt.Sprintf("%dx%d!", v.Width, v.Height), "-strip", "-quality")
quality := "85"
if v.Name == "optimized" && version == 1 {
quality = "80"
}
coder := "jpeg:"
if v.Name == "optimized" {
coder = "webp:"
}
args = append(args, quality, coder+v.Path)
if e = run(ctx, args...); e != nil {
return nil, e
}
}
return out, nil
}