forked from mtusi2026/mtusi2026lab6
273 lines
7.3 KiB
Go
273 lines
7.3 KiB
Go
package transform
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"errors"
|
|
"image"
|
|
"image/jpeg"
|
|
_ "image/png"
|
|
"io"
|
|
"math"
|
|
"net/http"
|
|
|
|
"github.com/deepteams/webp"
|
|
)
|
|
|
|
const (
|
|
// DefaultJPEGQuality is used for thumbnail and crop variants.
|
|
DefaultJPEGQuality = 85
|
|
// DefaultWebPQuality keeps the optimized variant visually close to the source while reducing its size.
|
|
DefaultWebPQuality = 82
|
|
// DefaultWebPMethod selects the encoder's balanced quality and CPU mode.
|
|
DefaultWebPMethod = 4
|
|
)
|
|
|
|
var (
|
|
ErrInvalidConfig = errors.New("invalid image transform configuration")
|
|
ErrUnsupportedMedia = errors.New("unsupported image media type")
|
|
ErrPayloadTooLarge = errors.New("image exceeds configured limits")
|
|
ErrInvalidImage = errors.New("invalid image data")
|
|
)
|
|
|
|
type Config struct {
|
|
MaxBytes int64
|
|
MaxPixels int64
|
|
JPEGQuality int
|
|
WebPQuality float32
|
|
WebPMethod int
|
|
}
|
|
|
|
type Variant struct {
|
|
Bytes []byte
|
|
ContentType string
|
|
Width int
|
|
Height int
|
|
SHA256 string
|
|
}
|
|
|
|
type Result struct {
|
|
Original Variant
|
|
Thumbnail Variant
|
|
Crop Variant
|
|
Optimized Variant
|
|
Orientation int
|
|
}
|
|
|
|
type Processor struct {
|
|
config Config
|
|
}
|
|
|
|
func DefaultConfig(maxBytes, maxPixels int64) Config {
|
|
return Config{
|
|
MaxBytes: maxBytes, MaxPixels: maxPixels,
|
|
JPEGQuality: DefaultJPEGQuality, WebPQuality: DefaultWebPQuality, WebPMethod: DefaultWebPMethod,
|
|
}
|
|
}
|
|
|
|
func NewProcessor(config Config) (*Processor, error) {
|
|
if config.MaxBytes < 1 || config.MaxPixels < 1 || config.JPEGQuality < 1 || config.JPEGQuality > 100 ||
|
|
config.WebPQuality < 1 || config.WebPQuality > 100 || config.WebPMethod < 0 || config.WebPMethod > 6 {
|
|
return nil, ErrInvalidConfig
|
|
}
|
|
return &Processor{config: config}, nil
|
|
}
|
|
|
|
func (p *Processor) Process(ctx context.Context, data []byte, declaredContentType string) (Result, error) {
|
|
if err := contextError(ctx); err != nil {
|
|
return Result{}, err
|
|
}
|
|
img, format, width, height, orientation, err := p.decode(ctx, data, declaredContentType)
|
|
if err != nil {
|
|
return Result{}, err
|
|
}
|
|
if err := contextError(ctx); err != nil {
|
|
return Result{}, err
|
|
}
|
|
|
|
oriented, err := applyOrientation(ctx, img, orientation)
|
|
if err != nil {
|
|
return Result{}, err
|
|
}
|
|
opaque, err := flattenWhite(ctx, oriented)
|
|
if err != nil {
|
|
return Result{}, err
|
|
}
|
|
result := Result{
|
|
Original: variant(data, format, width, height),
|
|
Orientation: orientation,
|
|
}
|
|
|
|
thumbnail, err := fitContext(ctx, opaque, 256, 256, false)
|
|
if err != nil {
|
|
return Result{}, err
|
|
}
|
|
result.Thumbnail, err = encodeJPEG(thumbnail, p.config.JPEGQuality)
|
|
if err != nil {
|
|
return Result{}, err
|
|
}
|
|
if err := contextError(ctx); err != nil {
|
|
return Result{}, err
|
|
}
|
|
|
|
crop := centeredSquare(opaque)
|
|
crop, err = resizeContext(ctx, crop, 128, 128)
|
|
if err != nil {
|
|
return Result{}, err
|
|
}
|
|
result.Crop, err = encodeJPEG(crop, p.config.JPEGQuality)
|
|
if err != nil {
|
|
return Result{}, err
|
|
}
|
|
if err := contextError(ctx); err != nil {
|
|
return Result{}, err
|
|
}
|
|
|
|
optimized, err := fitContext(ctx, opaque, 1280, 1280, false)
|
|
if err != nil {
|
|
return Result{}, err
|
|
}
|
|
result.Optimized, err = encodeWebP(optimized, p.config.WebPQuality, p.config.WebPMethod)
|
|
if err != nil {
|
|
return Result{}, err
|
|
}
|
|
if err := contextError(ctx); err != nil {
|
|
return Result{}, err
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
func (p *Processor) decode(
|
|
ctx context.Context,
|
|
data []byte,
|
|
declaredContentType string,
|
|
) (image.Image, string, int, int, int, error) {
|
|
if declaredContentType != "image/jpeg" && declaredContentType != "image/png" {
|
|
return nil, "", 0, 0, 0, ErrUnsupportedMedia
|
|
}
|
|
if len(data) == 0 {
|
|
return nil, "", 0, 0, 0, ErrInvalidImage
|
|
}
|
|
if int64(len(data)) > p.config.MaxBytes {
|
|
return nil, "", 0, 0, 0, ErrPayloadTooLarge
|
|
}
|
|
if http.DetectContentType(data) != declaredContentType {
|
|
return nil, "", 0, 0, 0, ErrUnsupportedMedia
|
|
}
|
|
config, format, err := image.DecodeConfig(contextReader{ctx: ctx, reader: bytes.NewReader(data)})
|
|
if contextErr := contextError(ctx); contextErr != nil {
|
|
return nil, "", 0, 0, 0, contextErr
|
|
}
|
|
if err != nil || contentType(format) != declaredContentType || config.Width < 1 || config.Height < 1 {
|
|
return nil, "", 0, 0, 0, ErrInvalidImage
|
|
}
|
|
if int64(config.Width) > p.config.MaxPixels/int64(config.Height) {
|
|
return nil, "", 0, 0, 0, ErrPayloadTooLarge
|
|
}
|
|
img, decodedFormat, err := image.Decode(contextReader{ctx: ctx, reader: bytes.NewReader(data)})
|
|
if contextErr := contextError(ctx); contextErr != nil {
|
|
return nil, "", 0, 0, 0, contextErr
|
|
}
|
|
if err != nil || decodedFormat != format {
|
|
return nil, "", 0, 0, 0, ErrInvalidImage
|
|
}
|
|
orientation := 1
|
|
if format == "jpeg" {
|
|
orientation, err = jpegOrientation(ctx, data)
|
|
if err != nil {
|
|
if contextErr := contextError(ctx); contextErr != nil {
|
|
return nil, "", 0, 0, 0, contextErr
|
|
}
|
|
return nil, "", 0, 0, 0, ErrInvalidImage
|
|
}
|
|
}
|
|
return img, declaredContentType, config.Width, config.Height, orientation, nil
|
|
}
|
|
|
|
type contextReader struct {
|
|
ctx context.Context
|
|
reader io.Reader
|
|
}
|
|
|
|
func (r contextReader) Read(buffer []byte) (int, error) {
|
|
if err := contextError(r.ctx); err != nil {
|
|
return 0, err
|
|
}
|
|
return r.reader.Read(buffer)
|
|
}
|
|
|
|
func contextError(ctx context.Context) error {
|
|
select {
|
|
case <-ctx.Done():
|
|
return ctx.Err()
|
|
default:
|
|
return nil
|
|
}
|
|
}
|
|
|
|
func contentType(format string) string {
|
|
switch format {
|
|
case "jpeg":
|
|
return "image/jpeg"
|
|
case "png":
|
|
return "image/png"
|
|
default:
|
|
return ""
|
|
}
|
|
}
|
|
|
|
func encodeJPEG(img image.Image, quality int) (Variant, error) {
|
|
var output bytes.Buffer
|
|
if err := jpeg.Encode(&output, img, &jpeg.Options{Quality: quality}); err != nil {
|
|
return Variant{}, err
|
|
}
|
|
bounds := img.Bounds()
|
|
return variant(output.Bytes(), "image/jpeg", bounds.Dx(), bounds.Dy()), nil
|
|
}
|
|
|
|
func encodeWebP(img image.Image, quality float32, method int) (Variant, error) {
|
|
var output bytes.Buffer
|
|
options := &webp.EncoderOptions{Quality: quality, Method: method}
|
|
if err := webp.Encode(&output, img, options); err != nil {
|
|
return Variant{}, err
|
|
}
|
|
bounds := img.Bounds()
|
|
return variant(output.Bytes(), "image/webp", bounds.Dx(), bounds.Dy()), nil
|
|
}
|
|
|
|
func variant(data []byte, contentType string, width, height int) Variant {
|
|
digest := sha256.Sum256(data)
|
|
return Variant{
|
|
Bytes: data, ContentType: contentType, Width: width, Height: height,
|
|
SHA256: hex.EncodeToString(digest[:]),
|
|
}
|
|
}
|
|
|
|
// EstimateMemoryWeight returns a conservative reservation for the input, decoded source,
|
|
// orientation and alpha copies, variant working buffer, and encoded variant buffers.
|
|
func EstimateMemoryWeight(inputBytes int64, width, height int) (int64, error) {
|
|
if inputBytes < 0 || width < 1 || height < 1 || int64(width) > math.MaxInt64/int64(height) {
|
|
return 0, ErrInvalidImage
|
|
}
|
|
pixels := int64(width) * int64(height)
|
|
optimizedPixels := fittedPixels(width, height, 1280, 1280)
|
|
thumbnailPixels := fittedPixels(width, height, 256, 256)
|
|
const cropPixels int64 = 128 * 128
|
|
if pixels > (math.MaxInt64-inputBytes)/16 {
|
|
return 0, ErrPayloadTooLarge
|
|
}
|
|
weight := inputBytes + pixels*16
|
|
variants := (optimizedPixels + thumbnailPixels + cropPixels) * 4
|
|
if variants > math.MaxInt64-weight {
|
|
return 0, ErrPayloadTooLarge
|
|
}
|
|
return weight + variants, nil
|
|
}
|
|
|
|
func fittedPixels(width, height, maxWidth, maxHeight int) int64 {
|
|
newWidth, newHeight := fitDimensions(width, height, maxWidth, maxHeight, false)
|
|
return int64(newWidth) * int64(newHeight)
|
|
}
|