Files
summercms/modules/album/variants.go

131 lines
3.6 KiB
Go

package album
import (
"bytes"
"context"
"fmt"
"image"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"math"
"strconv"
"git.golem15.com/golem15/summercms/modules/compass"
"git.golem15.com/golem15/summercms/modules/lagoon/attach/webp"
"gocloud.dev/blob"
"golang.org/x/image/draw"
_ "golang.org/x/image/webp"
)
// VariantWidths are the responsive WebP widths generated synchronously on
// raster image uploads. Uploads never upscale past the original width.
var VariantWidths = []int{480, 960, 1600}
// GenerateWebPVariants resizes img to each breakpoint in VariantWidths smaller
// than its original width (and, when no smaller breakpoint applies and the
// original is not already WebP, encodes a single WebP at the original width),
// writes each variant to bucket at media/<short-id>/<slug>-<width>w.webp, and
// returns the Variant records and written blob keys.
//
// If any encode or write fails, every variant written so far is deleted before
// returning the error.
func GenerateWebPVariants(
ctx context.Context,
cfg *compass.Config,
bucket *blob.Bucket,
shortID, slug string,
img image.Image,
origFormat string,
) ([]Variant, []string, error) {
if bucket == nil {
return nil, nil, fmt.Errorf("album: bucket is nil")
}
if img == nil {
return nil, nil, fmt.Errorf("album: image is nil")
}
bounds := img.Bounds()
origW := bounds.Dx()
origH := bounds.Dy()
if origW <= 0 || origH <= 0 {
return nil, nil, fmt.Errorf("album: invalid image dimensions %dx%d", origW, origH)
}
targets := make([]int, 0, len(VariantWidths))
for _, w := range VariantWidths {
if w < origW {
targets = append(targets, w)
}
}
if len(targets) == 0 && origFormat != webp.Format {
targets = append(targets, origW)
}
if len(targets) == 0 {
return []Variant{}, nil, nil
}
variants := make([]Variant, 0, len(targets))
writtenKeys := make([]string, 0, len(targets))
cleanup := func() {
_ = DeleteBlobs(context.WithoutCancel(ctx), bucket, writtenKeys)
}
for _, targetW := range targets {
var dst image.Image
var targetH int
if targetW == origW {
dst = img
targetH = origH
} else {
targetH = max(1, int(math.Round(float64(origH)*float64(targetW)/float64(origW))))
rgba := image.NewRGBA(image.Rect(0, 0, targetW, targetH))
draw.CatmullRom.Scale(rgba, rgba.Bounds(), img, bounds, draw.Over, nil)
dst = rgba
}
var buf bytes.Buffer
if err := webp.Encode(&buf, dst); err != nil {
cleanup()
return nil, nil, fmt.Errorf("album: encode %dw webp variant: %w", targetW, err)
}
key := fmt.Sprintf("%s/%s/%s-%sw.webp", BlobKeyPrefix, shortID, slug, strconv.Itoa(targetW))
if err := writeBytes(ctx, bucket, key, buf.Bytes(), webp.ContentType); err != nil {
cleanup()
return nil, nil, fmt.Errorf("album: write %dw webp variant: %w", targetW, err)
}
writtenKeys = append(writtenKeys, key)
variants = append(variants, Variant{
Width: targetW,
Height: targetH,
Key: key,
URL: blobKeyPublicURL(cfg, key),
Size: int64(buf.Len()),
ContentType: webp.ContentType,
})
}
return variants, writtenKeys, nil
}
func writeBytes(ctx context.Context, bucket *blob.Bucket, key string, data []byte, contentType string) error {
writeCtx, cancel := context.WithCancel(ctx)
defer cancel()
w, err := bucket.NewWriter(writeCtx, key, &blob.WriterOptions{ContentType: contentType})
if err != nil {
return err
}
if _, err := w.Write(data); err != nil {
cancel()
_ = w.Close()
_ = DeleteBlobs(context.WithoutCancel(ctx), bucket, []string{key})
return err
}
if err := w.Close(); err != nil {
_ = DeleteBlobs(context.WithoutCancel(ctx), bucket, []string{key})
return err
}
return nil
}