forked from mtusi2026/mtusi2026lab5
88 lines
2.4 KiB
Go
88 lines
2.4 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
|
"image"
|
|
"image/color"
|
|
"image/jpeg"
|
|
"image/png"
|
|
"os"
|
|
"os/exec"
|
|
"syscall"
|
|
)
|
|
|
|
type output struct {
|
|
meta domain.Variant
|
|
data []byte
|
|
}
|
|
|
|
func newOutput(name, ct string, data []byte, w, h int) output {
|
|
sum := sha256.Sum256(data)
|
|
return output{domain.Variant{Name: name, ContentType: ct, SizeBytes: int64(len(data)), Width: w, Height: h, SHA256: hex.EncodeToString(sum[:])}, data}
|
|
}
|
|
|
|
// Decode/re-encode drops EXIF/ICC/XMP; orientation is applied before this function.
|
|
func variants(ctx context.Context, im image.Image) ([]output, error) {
|
|
thumb, w, h, err := thumbnail(im)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out := []output{newOutput("thumbnail", "image/jpeg", thumb, w, h)}
|
|
b := im.Bounds()
|
|
side := min(b.Dx(), b.Dy())
|
|
x, y := b.Min.X+(b.Dx()-side)/2, b.Min.Y+(b.Dy()-side)/2
|
|
crop := resize(im, image.Rect(x, y, x+side, y+side), 128, 128)
|
|
var buf bytes.Buffer
|
|
if err = jpeg.Encode(&buf, crop, &jpeg.Options{Quality: 85}); err != nil {
|
|
return nil, err
|
|
}
|
|
out = append(out, newOutput("crop", "image/jpeg", bytes.Clone(buf.Bytes()), 128, 128))
|
|
w, h = b.Dx(), b.Dy()
|
|
if w > 1280 || h > 1280 {
|
|
if w >= h {
|
|
h = max(1, h*1280/w)
|
|
w = 1280
|
|
} else {
|
|
w = max(1, w*1280/h)
|
|
h = 1280
|
|
}
|
|
}
|
|
buf.Reset()
|
|
if err = png.Encode(&buf, resize(im, b, w, h)); err != nil {
|
|
return nil, err
|
|
}
|
|
f, err := os.CreateTemp("", "optimized-*.png")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer os.Remove(f.Name())
|
|
if _, err = f.Write(buf.Bytes()); err != nil {
|
|
f.Close()
|
|
return nil, err
|
|
}
|
|
if err = f.Close(); err != nil {
|
|
return nil, err
|
|
}
|
|
cmd := exec.CommandContext(ctx, "cwebp", "-quiet", "-q", "80", "-metadata", "none", "-o", "-", f.Name())
|
|
cmd.SysProcAttr = &syscall.SysProcAttr{Pdeathsig: syscall.SIGKILL}
|
|
data, err := cmd.Output()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return append(out, newOutput("optimized", "image/webp", data, w, h)), nil
|
|
}
|
|
func resize(im image.Image, b image.Rectangle, w, h int) *image.RGBA {
|
|
dst := image.NewRGBA(image.Rect(0, 0, w, h))
|
|
for y := 0; y < h; y++ {
|
|
for x := 0; x < w; x++ {
|
|
r, g, bl, a := im.At(b.Min.X+x*b.Dx()/w, b.Min.Y+y*b.Dy()/h).RGBA()
|
|
dst.SetRGBA(x, y, color.RGBA{uint8((r + 65535 - a) >> 8), uint8((g + 65535 - a) >> 8), uint8((bl + 65535 - a) >> 8), 255})
|
|
}
|
|
}
|
|
return dst
|
|
}
|