Files
2026-11-16 20:30:12 +03:00

138 lines
3.9 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package main
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"image"
"image/jpeg"
"math"
"golang.org/x/image/draw"
)
type VariantSpec struct {
Name string
ContentType string
Width int
Height int
Data []byte
SHA256 string
}
func encodeOptimizedJPEG(src image.Image, quality int) ([]byte, error) {
var buf bytes.Buffer
if err := jpeg.Encode(&buf, src, &jpeg.Options{Quality: quality}); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// processImage возвращает 4 варианта. Оригинал — byte-identical с входом.
// thumbnail 256x256 (fit, без искажения), crop 128x128 (center crop),
// optimized — JPEG q=70 без метаданных (WebP оставлен на усмотрение; см. отчёт).
func processImage(raw []byte, contentType string) ([]VariantSpec, error) {
src, _, err := image.Decode(bytes.NewReader(raw))
if err != nil {
return nil, err
}
out := make([]VariantSpec, 0, 4)
// original — ровно те байты, что пришли в staging.
sum := sha256.Sum256(raw)
out = append(out, VariantSpec{
Name: "original", ContentType: contentType,
Width: src.Bounds().Dx(), Height: src.Bounds().Dy(),
Data: raw, SHA256: hex.EncodeToString(sum[:]),
})
// thumbnail: fit в 256x160 с сохранением пропорций (для 16:10 — 256x160).
th := resizeFit(src, 256, 256)
if err := appendEncoded(&out, "thumbnail", "image/jpeg", th); err != nil {
return nil, err
}
// crop 128x128: центр-cover до меньшего квадрата.
cr := squareCover(src, 128)
if err := appendEncoded(&out, "crop", "image/jpeg", cr); err != nil {
return nil, err
}
// optimized
optBuf, err := encodeOptimizedJPEG(src, 70)
if err != nil {
return nil, err
}
optSum := sha256.Sum256(optBuf)
out = append(out, VariantSpec{
Name: "optimized", ContentType: "image/jpeg",
Width: src.Bounds().Dx(), Height: src.Bounds().Dy(),
Data: optBuf, SHA256: hex.EncodeToString(optSum[:]),
})
return out, nil
}
func appendEncoded(out *[]VariantSpec, name, ct string, img image.Image) error {
var buf bytes.Buffer
if err := jpeg.Encode(&buf, img, &jpeg.Options{Quality: 85}); err != nil {
return err
}
sum := sha256.Sum256(buf.Bytes())
*out = append(*out, VariantSpec{
Name: name, ContentType: ct,
Width: img.Bounds().Dx(), Height: img.Bounds().Dy(),
Data: buf.Bytes(), SHA256: hex.EncodeToString(sum[:]),
})
return nil
}
func resizeFit(src image.Image, maxW, maxH int) image.Image {
b := src.Bounds()
w, h := b.Dx(), b.Dy()
scale := float64(maxW) / float64(w)
if float64(maxH)/float64(h) < scale {
scale = float64(maxH) / float64(h)
}
if scale > 1 {
scale = 1
}
nw := int(math.Round(float64(w) * scale))
nh := int(math.Round(float64(h) * scale))
dst := image.NewRGBA(image.Rect(0, 0, nw, nh))
draw.CatmullRom.Scale(dst, dst.Bounds(), src, b, draw.Over, nil)
return dst
}
// squareCover масштабирует src так, чтобы покрыть квадрат size×size
// (min-масштаб по двум осям), затем центр-кроп до size×size.
// Результат — всегда ровно size×size.
func squareCover(src image.Image, size int) image.Image {
b := src.Bounds()
w, h := b.Dx(), b.Dy()
// scale — больший из двух, чтобы покрыть квадрат
scale := float64(size) / float64(w)
if float64(size)/float64(h) > scale {
scale = float64(size) / float64(h)
}
nw := int(math.Round(float64(w) * scale))
nh := int(math.Round(float64(h) * scale))
if nw < size {
nw = size
}
if nh < size {
nh = size
}
scaled := image.NewRGBA(image.Rect(0, 0, nw, nh))
draw.CatmullRom.Scale(scaled, scaled.Bounds(), src, b, draw.Over, nil)
// center-crop до size×size
x0 := (nw - size) / 2
y0 := (nh - size) / 2
dst := image.NewRGBA(image.Rect(0, 0, size, size))
draw.Draw(dst, dst.Bounds(), scaled,
image.Pt(x0, y0), draw.Src)
return dst
}