Files
mtusi2026lab5-fork/imaging.go
T

177 lines
3.9 KiB
Go

package main
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"image"
"image/draw"
"image/jpeg"
_ "image/png"
"github.com/gen2brain/webp"
"github.com/rwcarlsen/goexif/exif"
xdraw "golang.org/x/image/draw"
)
const (
jpegQuality = 85
webpQuality = 80
webpMethod = 4
)
var errInvalidImage = errors.New("invalid image")
type variantSpec struct {
name, contentType, ext string
box int
crop bool
}
var variantSpecs = []variantSpec{
{"thumbnail", "image/jpeg", "jpg", 256, false},
{"crop", "image/jpeg", "jpg", 128, true},
{"optimized", "image/webp", "webp", 1280, false},
}
type rendered struct {
spec variantSpec
data []byte
width, height int
sha256 string
}
func renderVariants(ctx context.Context, data []byte, maxPixels int64) ([]rendered, error) {
cfg, format, err := image.DecodeConfig(bytes.NewReader(data))
if err != nil || cfg.Width < 1 || cfg.Height < 1 {
return nil, errInvalidImage
}
if int64(cfg.Width)*int64(cfg.Height) > maxPixels {
return nil, errInvalidImage
}
src, _, err := image.Decode(bytes.NewReader(data))
if err != nil {
return nil, errInvalidImage
}
orient := 1
if format == "jpeg" {
orient = orientation(data)
}
src = shrink(src, 1280)
var out []rendered
for _, spec := range variantSpecs {
if err := ctx.Err(); err != nil {
return nil, err
}
img := render(src, cfg.Width, cfg.Height, orient, spec)
var buf bytes.Buffer
if spec.contentType == "image/webp" {
err = webp.Encode(&buf, img, webp.Options{Quality: webpQuality, Method: webpMethod})
} else {
err = jpeg.Encode(&buf, img, &jpeg.Options{Quality: jpegQuality})
}
if err != nil {
return nil, err
}
sum := sha256.Sum256(buf.Bytes())
b := img.Bounds()
out = append(out, rendered{spec: spec, data: buf.Bytes(), width: b.Dx(), height: b.Dy(), sha256: hex.EncodeToString(sum[:])})
}
return out, nil
}
func orientation(data []byte) int {
x, err := exif.Decode(bytes.NewReader(data))
if err != nil {
return 1
}
tag, err := x.Get(exif.Orientation)
if err != nil {
return 1
}
v, err := tag.Int(0)
if err != nil || v < 1 || v > 8 {
return 1
}
return v
}
func fit(w, h, box int) (int, int) {
if w <= box && h <= box {
return w, h
}
if w >= h {
return box, max(1, h*box/w)
}
return max(1, w*box/h), box
}
func shrink(src image.Image, limit int) image.Image {
for {
b := src.Bounds()
if max(b.Dx(), b.Dy())/2 < limit {
return src
}
dst := image.NewRGBA(image.Rect(0, 0, max(1, b.Dx()/2), max(1, b.Dy()/2)))
xdraw.ApproxBiLinear.Scale(dst, dst.Bounds(), src, b, xdraw.Src, nil)
src = dst
}
}
func render(src image.Image, sw, sh, orient int, spec variantSpec) *image.RGBA {
b := src.Bounds()
rect := b
var tw, th int
if spec.crop {
side := min(b.Dx(), b.Dy())
x0, y0 := b.Min.X+(b.Dx()-side)/2, b.Min.Y+(b.Dy()-side)/2
rect = image.Rect(x0, y0, x0+side, y0+side)
tw, th = spec.box, spec.box
} else if orient >= 5 {
th, tw = fit(sh, sw, spec.box)
} else {
tw, th = fit(sw, sh, spec.box)
}
dst := image.NewRGBA(image.Rect(0, 0, tw, th))
draw.Draw(dst, dst.Bounds(), image.White, image.Point{}, draw.Src)
xdraw.CatmullRom.Scale(dst, dst.Bounds(), src, rect, xdraw.Over, nil)
return orientImage(dst, orient)
}
func orientImage(img *image.RGBA, o int) *image.RGBA {
if o <= 1 {
return img
}
w, h := img.Bounds().Dx(), img.Bounds().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 nx, ny int
switch o {
case 2:
nx, ny = w-1-x, y
case 3:
nx, ny = w-1-x, h-1-y
case 4:
nx, ny = x, h-1-y
case 5:
nx, ny = y, x
case 6:
nx, ny = h-1-y, x
case 7:
nx, ny = h-1-y, w-1-x
case 8:
nx, ny = y, w-1-x
}
copy(dst.Pix[dst.PixOffset(nx, ny):dst.PixOffset(nx, ny)+4], img.Pix[img.PixOffset(x, y):img.PixOffset(x, y)+4])
}
}
return dst
}