Files
mtusi2026lab5/internal/imageprocessor/processor.go
T

99 lines
3.4 KiB
Go

// Package imageprocessor creates bounded contract variants with no client-controlled paths.
package imageprocessor
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"image"
"image/color"
"image/draw"
"image/jpeg"
"image/png"
"os/exec"
"github.com/disintegration/imaging"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/model/dto"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/pipeline"
)
// Processor generates JPEGs in-process and WebP through a cancellable bounded encoder.
type Processor struct {
webp string
}
// New resolves the required encoder before accepting work.
func New() (*Processor, error) {
path, err := exec.LookPath("cwebp")
if err != nil {
return nil, fmt.Errorf("cwebp encoder is required")
}
return &Processor{webp: path}, nil
}
// Process verifies dimensions before decode, applies EXIF orientation and strips metadata.
func (p *Processor) Process(ctx context.Context, source []byte) ([]pipeline.Output, error) {
cfg, format, err := image.DecodeConfig(bytes.NewReader(source))
if err != nil || (format != "png" && format != "jpeg") || len(source) > 10*1024*1024 || int64(cfg.Width)*int64(cfg.Height) > 40_000_000 {
return nil, pipeline.ErrInvalidImage
}
if err := ctx.Err(); err != nil {
return nil, err
}
decoded, err := imaging.Decode(bytes.NewReader(source), imaging.AutoOrientation(true))
if err != nil {
return nil, pipeline.ErrInvalidImage
}
bounds := decoded.Bounds()
white := image.NewNRGBA(image.Rect(0, 0, bounds.Dx(), bounds.Dy()))
draw.Draw(white, white.Bounds(), image.NewUniform(color.White), image.Point{}, draw.Src)
draw.Draw(white, white.Bounds(), decoded, bounds.Min, draw.Over)
thumbnail := fit(white, 256)
crop := imaging.Fill(white, 128, 128, imaging.Center, imaging.Lanczos)
optimized := fit(white, 1280)
outputs := make([]pipeline.Output, 0, 3)
for _, item := range []struct {
name string
picture image.Image
}{{"thumbnail", thumbnail}, {"crop", crop}} {
if err := ctx.Err(); err != nil {
return nil, err
}
var encoded bytes.Buffer
if err := jpeg.Encode(&encoded, item.picture, &jpeg.Options{Quality: 85}); err != nil {
return nil, err
}
outputs = append(outputs, output(item.name, "image/jpeg", item.picture.Bounds(), encoded.Bytes()))
}
var input bytes.Buffer
if err := png.Encode(&input, optimized); err != nil {
return nil, err
}
command := exec.CommandContext(ctx, p.webp, "-quiet", "-q", "80", "-metadata", "none", "-o", "-", "--", "-")
command.Stdin = &input
encoded, err := command.Output()
if err != nil {
return nil, fmt.Errorf("webp encoding failed: %w", err)
}
return append(outputs, output("optimized", "image/webp", optimized.Bounds(), encoded)), nil
}
// fit floors dimensions and never enlarges a small source.
func fit(source image.Image, limit int) image.Image {
width, height := source.Bounds().Dx(), source.Bounds().Dy()
largest := max(width, height)
if largest <= limit {
return source
}
return imaging.Resize(source, max(1, width*limit/largest), max(1, height*limit/largest), imaging.Lanczos)
}
// output derives immutable variant metadata from the actual encoded result.
func output(name, mime string, bounds image.Rectangle, data []byte) pipeline.Output {
sum := sha256.Sum256(data)
return pipeline.Output{Metadata: dto.Variant{Name: name, ContentType: mime, Width: bounds.Dx(), Height: bounds.Dy(), SizeBytes: int64(len(data)), SHA256: hex.EncodeToString(sum[:])}, Bytes: data}
}