// Package imaging строит варианты вложения по контракту lab5. // // thumbnail JPEG, вписан в 256×256 с сохранением пропорций, без увеличения, // EXIF orientation применён, alpha компонуется на белый, // размеры округляются вниз, минимум 1 px (320×200 → 256×160) // crop JPEG, центрированный квадрат 128×128 (маленькие увеличиваются) // optimized WebP, вписан в 1280×1280 без увеличения; lossy, качество WEBP_QUALITY, // метаданные удалены (cwebp -metadata none; пиксели и так // перекодированы из декодированного изображения, EXIF не переносится) // // Все кодировщики детерминированы: одинаковый вход даёт одинаковые байты, поэтому // повтор job перезаписывает объект тем же содержимым. package imaging import ( "bytes" "context" "crypto/sha256" "encoding/binary" "encoding/hex" "errors" "fmt" "image" "image/color" "image/draw" "image/jpeg" "image/png" "os" "os/exec" "path/filepath" xdraw "golang.org/x/image/draw" ) // ErrDecode — изображение не декодируется: постоянная ошибка (повтор не поможет). var ErrDecode = errors.New("cannot decode image") // Params — параметры версии pipeline. Новая версия может менять их, не трогая // уже опубликованные результаты старой (ключ эффекта включает версию). type Params struct { ThumbQuality int CropQuality int WebPQuality int } // ParamsFor — параметры по номеру версии pipeline. func ParamsFor(version, webpQuality int) Params { p := Params{ThumbQuality: 85, CropQuality: 85, WebPQuality: webpQuality} if version >= 2 { // v2 (трек 5): чуть выше качество превью — другой, но детерминированный результат. p.ThumbQuality, p.CropQuality = 92, 92 } return p } // Output — закодированный вариант. type Output struct { Name string ContentType string Data []byte Width int Height int SHA256 string } func newOutput(name, ctype string, data []byte, w, h int) Output { sum := sha256.Sum256(data) return Output{Name: name, ContentType: ctype, Data: data, Width: w, Height: h, SHA256: hex.EncodeToString(sum[:])} } // Decode декодирует оригинал, применяет EXIF orientation (JPEG) и компонует // прозрачность на белый фон. func Decode(data []byte) (*image.RGBA, error) { src, _, err := image.Decode(bytes.NewReader(data)) if err != nil { return nil, fmt.Errorf("%w: %v", ErrDecode, err) } b := src.Bounds() // Непрозрачный RGBA (типичный PNG RGB) уже готов: вторая полноразмерная копия // (4 байта × пиксель) не нужна — для 36 Мпикс это 137 MiB памяти worker. if rgba, ok := src.(*image.RGBA); ok && b.Min == (image.Point{}) && rgba.Opaque() { return Orient(rgba, ExifOrientation(data)), nil } out := image.NewRGBA(image.Rect(0, 0, b.Dx(), b.Dy())) draw.Draw(out, out.Bounds(), image.NewUniform(color.White), image.Point{}, draw.Src) draw.Draw(out, out.Bounds(), src, b.Min, draw.Over) // alpha → на белый return Orient(out, ExifOrientation(data)), nil } // FitSize — вписать w×h в box×box с сохранением пропорций; без увеличения, // если allowUpscale=false; округление вниз, минимум 1. func FitSize(w, h, box int, allowUpscale bool) (int, int) { if !allowUpscale && w <= box && h <= box { return w, h } if w >= h { nh := h * box / w return box, max(1, nh) } nw := w * box / h return max(1, nw), box } func resize(src image.Image, w, h int) *image.RGBA { dst := image.NewRGBA(image.Rect(0, 0, w, h)) xdraw.CatmullRom.Scale(dst, dst.Bounds(), src, src.Bounds(), xdraw.Src, nil) return dst } func encodeJPEG(img image.Image, quality int) ([]byte, error) { var b bytes.Buffer if err := jpeg.Encode(&b, img, &jpeg.Options{Quality: quality}); err != nil { return nil, err } return b.Bytes(), nil } // Thumbnail — JPEG, вписан в 256×256 без увеличения. func Thumbnail(img *image.RGBA, p Params) (Output, error) { w, h := FitSize(img.Bounds().Dx(), img.Bounds().Dy(), 256, false) var src image.Image = img if w != img.Bounds().Dx() || h != img.Bounds().Dy() { src = resize(img, w, h) } data, err := encodeJPEG(src, p.ThumbQuality) if err != nil { return Output{}, err } return newOutput("thumbnail", "image/jpeg", data, w, h), nil } // Crop — JPEG, центрированный квадрат 128×128 (маленькие исходники увеличиваются). func Crop(img *image.RGBA, p Params) (Output, error) { b := img.Bounds() side := min(b.Dx(), b.Dy()) x0 := b.Min.X + (b.Dx()-side)/2 y0 := b.Min.Y + (b.Dy()-side)/2 sq := img.SubImage(image.Rect(x0, y0, x0+side, y0+side)) data, err := encodeJPEG(resize(sq, 128, 128), p.CropQuality) if err != nil { return Output{}, err } return newOutput("crop", "image/jpeg", data, 128, 128), nil } // WebPEncoder кодирует RGBA в WebP. type WebPEncoder func(ctx context.Context, img image.Image, quality int) ([]byte, error) // CWebP — кодировщик через cwebp (libwebp-tools): lossy, -metadata none. // Вход — PNG во временном каталоге процесса (эфемерный, удаляется сразу). func CWebP(ctx context.Context, img image.Image, quality int) ([]byte, error) { dir, err := os.MkdirTemp("", "webp-") if err != nil { return nil, err } defer os.RemoveAll(dir) in, out := filepath.Join(dir, "in.png"), filepath.Join(dir, "out.webp") f, err := os.Create(in) if err != nil { return nil, err } enc := png.Encoder{CompressionLevel: png.BestSpeed} if err := enc.Encode(f, img); err != nil { f.Close() return nil, err } f.Close() cmd := exec.CommandContext(ctx, "cwebp", "-quiet", "-q", fmt.Sprint(quality), "-m", "4", "-metadata", "none", in, "-o", out) if msg, err := cmd.CombinedOutput(); err != nil { return nil, fmt.Errorf("cwebp: %v: %s", err, bytes.TrimSpace(msg)) } return os.ReadFile(out) } // Optimized — WebP, вписан в 1280×1280 без увеличения. func Optimized(ctx context.Context, img *image.RGBA, p Params, enc WebPEncoder) (Output, error) { w, h := FitSize(img.Bounds().Dx(), img.Bounds().Dy(), 1280, false) var src image.Image = img if w != img.Bounds().Dx() || h != img.Bounds().Dy() { src = resize(img, w, h) } data, err := enc(ctx, src, p.WebPQuality) if err != nil { return Output{}, err } if len(data) < 12 || string(data[0:4]) != "RIFF" || string(data[8:12]) != "WEBP" { return Output{}, errors.New("encoder produced non-WebP data") } return newOutput("optimized", "image/webp", data, w, h), nil } // --- EXIF orientation --- // ExifOrientation возвращает тег 0x0112 из APP1 Exif JPEG (1 — нет поворота). func ExifOrientation(data []byte) int { if len(data) < 4 || data[0] != 0xFF || data[1] != 0xD8 { return 1 } i := 2 for i+4 <= len(data) && data[i] == 0xFF { marker := data[i+1] if marker == 0xDA || marker == 0xD9 { break } segLen := int(binary.BigEndian.Uint16(data[i+2 : i+4])) if segLen < 2 || i+2+segLen > len(data) { break } seg := data[i+4 : i+2+segLen] if marker == 0xE1 && len(seg) > 14 && string(seg[:6]) == "Exif\x00\x00" { if o := tiffOrientation(seg[6:]); o >= 1 && o <= 8 { return o } } i += 2 + segLen } return 1 } func tiffOrientation(t []byte) int { if len(t) < 8 { return 1 } var bo binary.ByteOrder switch string(t[:2]) { case "II": bo = binary.LittleEndian case "MM": bo = binary.BigEndian default: return 1 } off := int(bo.Uint32(t[4:8])) if off+2 > len(t) { return 1 } n := int(bo.Uint16(t[off : off+2])) for k := 0; k < n; k++ { e := off + 2 + 12*k if e+12 > len(t) { return 1 } if bo.Uint16(t[e:e+2]) == 0x0112 { return int(bo.Uint16(t[e+8 : e+10])) } } return 1 } // Orient применяет EXIF orientation 1..8 (поворот/отражение). func Orient(src *image.RGBA, o int) *image.RGBA { if o <= 1 || o > 8 { return src } b := src.Bounds() w, h := b.Dx(), b.Dy() dw, dh := w, h if o >= 5 { dw, dh = h, w } dst := image.NewRGBA(image.Rect(0, 0, dw, dh)) for y := 0; y < h; y++ { for x := 0; x < w; x++ { var dx, dy int switch o { case 2: dx, dy = w-1-x, y case 3: dx, dy = w-1-x, h-1-y case 4: dx, dy = x, h-1-y case 5: dx, dy = y, x case 6: dx, dy = h-1-y, x case 7: dx, dy = h-1-y, w-1-x case 8: dx, dy = y, w-1-x } dst.SetRGBA(dx, dy, src.RGBAAt(b.Min.X+x, b.Min.Y+y)) } } return dst } // SHA256Hex — lowercase hex SHA-256. func SHA256Hex(data []byte) string { sum := sha256.Sum256(data) return hex.EncodeToString(sum[:]) }