forked from mtusi2026/mtusi2026lab6
chore: import lab5 baseline
This commit is contained in:
@@ -0,0 +1,169 @@
|
||||
package transform
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"image"
|
||||
"image/color"
|
||||
)
|
||||
|
||||
var errInvalidEXIF = errors.New("invalid EXIF metadata")
|
||||
|
||||
func jpegOrientation(ctx context.Context, data []byte) (int, error) {
|
||||
if len(data) < 2 || data[0] != 0xff || data[1] != 0xd8 {
|
||||
return 0, errInvalidEXIF
|
||||
}
|
||||
for offset := 2; offset < len(data); {
|
||||
if err := contextError(ctx); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if data[offset] != 0xff {
|
||||
return 0, errInvalidEXIF
|
||||
}
|
||||
for offset < len(data) && data[offset] == 0xff {
|
||||
offset++
|
||||
}
|
||||
if offset >= len(data) {
|
||||
return 0, errInvalidEXIF
|
||||
}
|
||||
marker := data[offset]
|
||||
offset++
|
||||
if marker == 0xd9 || marker == 0xda {
|
||||
return 1, nil
|
||||
}
|
||||
if marker == 0x01 || marker >= 0xd0 && marker <= 0xd7 {
|
||||
continue
|
||||
}
|
||||
if offset+2 > len(data) {
|
||||
return 0, errInvalidEXIF
|
||||
}
|
||||
length := int(binary.BigEndian.Uint16(data[offset : offset+2]))
|
||||
if length < 2 || offset+length > len(data) {
|
||||
return 0, errInvalidEXIF
|
||||
}
|
||||
payload := data[offset+2 : offset+length]
|
||||
offset += length
|
||||
if marker != 0xe1 || len(payload) < 6 || string(payload[:6]) != "Exif\x00\x00" {
|
||||
continue
|
||||
}
|
||||
return tiffOrientation(ctx, payload[6:])
|
||||
}
|
||||
return 1, nil
|
||||
}
|
||||
|
||||
func tiffOrientation(ctx context.Context, data []byte) (int, error) {
|
||||
if len(data) < 8 {
|
||||
return 0, errInvalidEXIF
|
||||
}
|
||||
var order binary.ByteOrder
|
||||
switch string(data[:2]) {
|
||||
case "II":
|
||||
order = binary.LittleEndian
|
||||
case "MM":
|
||||
order = binary.BigEndian
|
||||
default:
|
||||
return 0, errInvalidEXIF
|
||||
}
|
||||
if order.Uint16(data[2:4]) != 42 {
|
||||
return 0, errInvalidEXIF
|
||||
}
|
||||
ifdOffset := uint64(order.Uint32(data[4:8]))
|
||||
if ifdOffset > uint64(len(data)-2) {
|
||||
return 0, errInvalidEXIF
|
||||
}
|
||||
count := uint64(order.Uint16(data[ifdOffset : ifdOffset+2]))
|
||||
entriesStart := ifdOffset + 2
|
||||
if count > (uint64(len(data))-entriesStart)/12 {
|
||||
return 0, errInvalidEXIF
|
||||
}
|
||||
for index := uint64(0); index < count; index++ {
|
||||
if err := contextError(ctx); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
entry := data[entriesStart+index*12 : entriesStart+(index+1)*12]
|
||||
if order.Uint16(entry[:2]) != 0x0112 {
|
||||
continue
|
||||
}
|
||||
if order.Uint16(entry[2:4]) != 3 || order.Uint32(entry[4:8]) != 1 {
|
||||
return 0, errInvalidEXIF
|
||||
}
|
||||
orientation := int(order.Uint16(entry[8:10]))
|
||||
if orientation < 1 || orientation > 8 {
|
||||
return 0, errInvalidEXIF
|
||||
}
|
||||
return orientation, nil
|
||||
}
|
||||
return 1, nil
|
||||
}
|
||||
|
||||
func applyOrientation(ctx context.Context, source image.Image, orientation int) (*image.NRGBA, error) {
|
||||
bounds := source.Bounds()
|
||||
width, height := bounds.Dx(), bounds.Dy()
|
||||
outputWidth, outputHeight := width, height
|
||||
if orientation >= 5 {
|
||||
outputWidth, outputHeight = height, width
|
||||
}
|
||||
output := image.NewNRGBA(image.Rect(0, 0, outputWidth, outputHeight))
|
||||
for y := 0; y < outputHeight; y++ {
|
||||
if err := contextError(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for x := 0; x < outputWidth; x++ {
|
||||
if x&255 == 0 {
|
||||
if err := contextError(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
sourceX, sourceY := orientedSourcePoint(x, y, width, height, orientation)
|
||||
output.Set(x, y, source.At(bounds.Min.X+sourceX, bounds.Min.Y+sourceY))
|
||||
}
|
||||
}
|
||||
return output, nil
|
||||
}
|
||||
|
||||
func orientedSourcePoint(x, y, width, height, orientation int) (int, int) {
|
||||
switch orientation {
|
||||
case 2:
|
||||
return width - 1 - x, y
|
||||
case 3:
|
||||
return width - 1 - x, height - 1 - y
|
||||
case 4:
|
||||
return x, height - 1 - y
|
||||
case 5:
|
||||
return y, x
|
||||
case 6:
|
||||
return y, height - 1 - x
|
||||
case 7:
|
||||
return width - 1 - y, height - 1 - x
|
||||
case 8:
|
||||
return width - 1 - y, x
|
||||
default:
|
||||
return x, y
|
||||
}
|
||||
}
|
||||
|
||||
func flattenWhite(ctx context.Context, source image.Image) (*image.NRGBA, error) {
|
||||
bounds := source.Bounds()
|
||||
output := image.NewNRGBA(image.Rect(0, 0, bounds.Dx(), bounds.Dy()))
|
||||
for y := 0; y < bounds.Dy(); y++ {
|
||||
if err := contextError(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for x := 0; x < bounds.Dx(); x++ {
|
||||
if x&255 == 0 {
|
||||
if err := contextError(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
r, g, b, a := source.At(bounds.Min.X+x, bounds.Min.Y+y).RGBA()
|
||||
output.SetNRGBA(x, y, color.NRGBA{
|
||||
R: uint8((r + 0xffff - a) / 0x101),
|
||||
G: uint8((g + 0xffff - a) / 0x101),
|
||||
B: uint8((b + 0xffff - a) / 0x101),
|
||||
A: 0xff,
|
||||
})
|
||||
}
|
||||
}
|
||||
return output, nil
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
package transform
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"testing"
|
||||
|
||||
"github.com/deepteams/webp"
|
||||
)
|
||||
|
||||
func TestProcessProducesExpectedVariants(t *testing.T) {
|
||||
source := image.NewNRGBA(image.Rect(0, 0, 320, 200))
|
||||
fillGradient(source)
|
||||
data := encodePNG(t, source)
|
||||
processor := newTestProcessor(t, int64(len(data))+1, 320*200)
|
||||
|
||||
result, err := processor.Process(context.Background(), data, "image/png")
|
||||
if err != nil {
|
||||
t.Fatalf("process image: %v", err)
|
||||
}
|
||||
|
||||
assertVariant(t, result.Original, "image/png", 320, 200)
|
||||
assertVariant(t, result.Thumbnail, "image/jpeg", 256, 160)
|
||||
assertVariant(t, result.Crop, "image/jpeg", 128, 128)
|
||||
assertVariant(t, result.Optimized, "image/webp", 320, 200)
|
||||
if !bytes.Equal(result.Original.Bytes, data) {
|
||||
t.Fatal("original bytes changed")
|
||||
}
|
||||
digest := sha256.Sum256(data)
|
||||
if result.Original.SHA256 != hex.EncodeToString(digest[:]) {
|
||||
t.Fatalf("unexpected original digest: %s", result.Original.SHA256)
|
||||
}
|
||||
if _, err := webp.Decode(bytes.NewReader(result.Optimized.Bytes)); err != nil {
|
||||
t.Fatalf("decode optimized WebP: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessDoesNotUpscaleFitVariants(t *testing.T) {
|
||||
source := image.NewNRGBA(image.Rect(0, 0, 64, 32))
|
||||
fillGradient(source)
|
||||
data := encodePNG(t, source)
|
||||
processor := newTestProcessor(t, int64(len(data))+1, 64*32)
|
||||
|
||||
result, err := processor.Process(context.Background(), data, "image/png")
|
||||
if err != nil {
|
||||
t.Fatalf("process image: %v", err)
|
||||
}
|
||||
|
||||
assertVariant(t, result.Thumbnail, "image/jpeg", 64, 32)
|
||||
assertVariant(t, result.Optimized, "image/webp", 64, 32)
|
||||
assertVariant(t, result.Crop, "image/jpeg", 128, 128)
|
||||
}
|
||||
|
||||
func TestFlattenWhiteCompositesAlpha(t *testing.T) {
|
||||
source := image.NewNRGBA(image.Rect(0, 0, 2, 1))
|
||||
source.SetNRGBA(0, 0, color.NRGBA{R: 10, G: 20, B: 30, A: 0})
|
||||
source.SetNRGBA(1, 0, color.NRGBA{R: 100, G: 50, B: 0, A: 128})
|
||||
|
||||
result, err := flattenWhite(context.Background(), source)
|
||||
if err != nil {
|
||||
t.Fatalf("flatten image: %v", err)
|
||||
}
|
||||
if got := result.NRGBAAt(0, 0); got != (color.NRGBA{R: 255, G: 255, B: 255, A: 255}) {
|
||||
t.Fatalf("transparent pixel: got %#v", got)
|
||||
}
|
||||
if got := result.NRGBAAt(1, 0); got != (color.NRGBA{R: 177, G: 152, B: 127, A: 255}) {
|
||||
t.Fatalf("semi-transparent pixel: got %#v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessAppliesEXIFOrientation(t *testing.T) {
|
||||
source := image.NewNRGBA(image.Rect(0, 0, 3, 2))
|
||||
fillGradient(source)
|
||||
data := injectOrientation(t, encodeJPEGForTest(t, source), 6)
|
||||
processor := newTestProcessor(t, int64(len(data))+1, 3*2)
|
||||
|
||||
result, err := processor.Process(context.Background(), data, "image/jpeg")
|
||||
if err != nil {
|
||||
t.Fatalf("process image: %v", err)
|
||||
}
|
||||
|
||||
if result.Orientation != 6 {
|
||||
t.Fatalf("orientation: got %d, want 6", result.Orientation)
|
||||
}
|
||||
assertVariant(t, result.Original, "image/jpeg", 3, 2)
|
||||
assertVariant(t, result.Thumbnail, "image/jpeg", 2, 3)
|
||||
assertVariant(t, result.Optimized, "image/webp", 2, 3)
|
||||
}
|
||||
|
||||
func TestProcessRejectsInvalidInputs(t *testing.T) {
|
||||
valid := encodePNG(t, image.NewNRGBA(image.Rect(0, 0, 11, 10)))
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
data []byte
|
||||
contentType string
|
||||
maxPixels int64
|
||||
want error
|
||||
}{
|
||||
{name: "MIME mismatch", data: valid, contentType: "image/jpeg", maxPixels: 200, want: ErrUnsupportedMedia},
|
||||
{name: "unsupported MIME", data: valid, contentType: "image/gif", maxPixels: 200, want: ErrUnsupportedMedia},
|
||||
{name: "pixel limit", data: valid, contentType: "image/png", maxPixels: 100, want: ErrPayloadTooLarge},
|
||||
{name: "corrupted", data: valid[:len(valid)-12], contentType: "image/png", maxPixels: 200, want: ErrInvalidImage},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
processor := newTestProcessor(t, int64(len(valid))+1, test.maxPixels)
|
||||
_, err := processor.Process(context.Background(), test.data, test.contentType)
|
||||
if !errors.Is(err, test.want) {
|
||||
t.Fatalf("error: got %v, want %v", err, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessIsDeterministic(t *testing.T) {
|
||||
source := image.NewNRGBA(image.Rect(0, 0, 48, 31))
|
||||
fillGradient(source)
|
||||
data := encodePNG(t, source)
|
||||
processor := newTestProcessor(t, int64(len(data))+1, 48*31)
|
||||
|
||||
first, err := processor.Process(context.Background(), data, "image/png")
|
||||
if err != nil {
|
||||
t.Fatalf("first process: %v", err)
|
||||
}
|
||||
second, err := processor.Process(context.Background(), data, "image/png")
|
||||
if err != nil {
|
||||
t.Fatalf("second process: %v", err)
|
||||
}
|
||||
|
||||
for name, variants := range map[string][2]Variant{
|
||||
"thumbnail": {first.Thumbnail, second.Thumbnail},
|
||||
"crop": {first.Crop, second.Crop},
|
||||
"optimized": {first.Optimized, second.Optimized},
|
||||
} {
|
||||
if !bytes.Equal(variants[0].Bytes, variants[1].Bytes) {
|
||||
t.Fatalf("%s bytes differ", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessHonorsCanceledContext(t *testing.T) {
|
||||
processor := newTestProcessor(t, 1024, 100)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
_, err := processor.Process(ctx, []byte("unused"), "image/png")
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("error: got %v, want %v", err, context.Canceled)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResizeStopsAfterCancellation(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
source := cancelingImage{
|
||||
Image: image.NewNRGBA(image.Rect(0, 0, 256, 256)),
|
||||
cancel: cancel,
|
||||
}
|
||||
_, err := resizeContext(ctx, source, 128, 128)
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("error: got %v, want %v", err, context.Canceled)
|
||||
}
|
||||
}
|
||||
|
||||
type cancelingImage struct {
|
||||
image.Image
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func (i cancelingImage) At(x, y int) color.Color {
|
||||
i.cancel()
|
||||
return i.Image.At(x, y)
|
||||
}
|
||||
|
||||
func TestEstimateMemoryWeight(t *testing.T) {
|
||||
weight, err := EstimateMemoryWeight(1000, 320, 200)
|
||||
if err != nil {
|
||||
t.Fatalf("estimate memory: %v", err)
|
||||
}
|
||||
want := int64(1000 + 320*200*16 + (320*200+256*160+128*128)*4)
|
||||
if weight != want {
|
||||
t.Fatalf("weight: got %d, want %d", weight, want)
|
||||
}
|
||||
}
|
||||
|
||||
func newTestProcessor(t *testing.T, maxBytes, maxPixels int64) *Processor {
|
||||
t.Helper()
|
||||
processor, err := NewProcessor(DefaultConfig(maxBytes, maxPixels))
|
||||
if err != nil {
|
||||
t.Fatalf("new processor: %v", err)
|
||||
}
|
||||
return processor
|
||||
}
|
||||
|
||||
func assertVariant(t *testing.T, variant Variant, contentType string, width, height int) {
|
||||
t.Helper()
|
||||
if variant.ContentType != contentType || variant.Width != width || variant.Height != height {
|
||||
t.Fatalf("variant: got type=%s dimensions=%dx%d, want type=%s dimensions=%dx%d",
|
||||
variant.ContentType, variant.Width, variant.Height, contentType, width, height)
|
||||
}
|
||||
if len(variant.Bytes) == 0 || variant.SHA256 == "" {
|
||||
t.Fatal("variant has no bytes or digest")
|
||||
}
|
||||
}
|
||||
|
||||
func fillGradient(img *image.NRGBA) {
|
||||
for y := 0; y < img.Bounds().Dy(); y++ {
|
||||
for x := 0; x < img.Bounds().Dx(); x++ {
|
||||
img.SetNRGBA(x, y, color.NRGBA{R: uint8(x), G: uint8(y), B: uint8(x + y), A: 255})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func encodePNG(t *testing.T, img image.Image) []byte {
|
||||
t.Helper()
|
||||
var output bytes.Buffer
|
||||
if err := png.Encode(&output, img); err != nil {
|
||||
t.Fatalf("encode PNG: %v", err)
|
||||
}
|
||||
return output.Bytes()
|
||||
}
|
||||
|
||||
func encodeJPEGForTest(t *testing.T, img image.Image) []byte {
|
||||
t.Helper()
|
||||
var output bytes.Buffer
|
||||
if err := jpeg.Encode(&output, img, &jpeg.Options{Quality: 100}); err != nil {
|
||||
t.Fatalf("encode JPEG: %v", err)
|
||||
}
|
||||
return output.Bytes()
|
||||
}
|
||||
|
||||
func injectOrientation(t *testing.T, data []byte, orientation uint16) []byte {
|
||||
t.Helper()
|
||||
if len(data) < 2 || data[0] != 0xff || data[1] != 0xd8 {
|
||||
t.Fatal("not a JPEG")
|
||||
}
|
||||
tiff := make([]byte, 26)
|
||||
copy(tiff[:2], "II")
|
||||
binary.LittleEndian.PutUint16(tiff[2:4], 42)
|
||||
binary.LittleEndian.PutUint32(tiff[4:8], 8)
|
||||
binary.LittleEndian.PutUint16(tiff[8:10], 1)
|
||||
binary.LittleEndian.PutUint16(tiff[10:12], 0x0112)
|
||||
binary.LittleEndian.PutUint16(tiff[12:14], 3)
|
||||
binary.LittleEndian.PutUint32(tiff[14:18], 1)
|
||||
binary.LittleEndian.PutUint16(tiff[18:20], orientation)
|
||||
payload := append([]byte("Exif\x00\x00"), tiff...)
|
||||
segment := []byte{0xff, 0xe1, 0, 0}
|
||||
binary.BigEndian.PutUint16(segment[2:4], uint16(len(payload)+2))
|
||||
result := make([]byte, 0, len(data)+len(segment)+len(payload))
|
||||
result = append(result, data[:2]...)
|
||||
result = append(result, segment...)
|
||||
result = append(result, payload...)
|
||||
return append(result, data[2:]...)
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package transform
|
||||
|
||||
import (
|
||||
"context"
|
||||
"image"
|
||||
"image/color"
|
||||
)
|
||||
|
||||
func fitContext(
|
||||
ctx context.Context,
|
||||
source image.Image,
|
||||
maxWidth int,
|
||||
maxHeight int,
|
||||
upscale bool,
|
||||
) (*image.NRGBA, error) {
|
||||
bounds := source.Bounds()
|
||||
width, height := fitDimensions(bounds.Dx(), bounds.Dy(), maxWidth, maxHeight, upscale)
|
||||
return resizeContext(ctx, source, width, height)
|
||||
}
|
||||
|
||||
func fitDimensions(width, height, maxWidth, maxHeight int, upscale bool) (int, int) {
|
||||
if !upscale && width <= maxWidth && height <= maxHeight {
|
||||
return width, height
|
||||
}
|
||||
if int64(width)*int64(maxHeight) > int64(height)*int64(maxWidth) {
|
||||
newHeight := max(1, int(int64(height)*int64(maxWidth)/int64(width)))
|
||||
return maxWidth, newHeight
|
||||
}
|
||||
newWidth := max(1, int(int64(width)*int64(maxHeight)/int64(height)))
|
||||
return newWidth, maxHeight
|
||||
}
|
||||
|
||||
func centeredSquare(source image.Image) image.Image {
|
||||
bounds := source.Bounds()
|
||||
size := min(bounds.Dx(), bounds.Dy())
|
||||
left := bounds.Min.X + (bounds.Dx()-size)/2
|
||||
top := bounds.Min.Y + (bounds.Dy()-size)/2
|
||||
return croppedImage{source: source, bounds: image.Rect(0, 0, size, size), offset: image.Pt(left, top)}
|
||||
}
|
||||
|
||||
type croppedImage struct {
|
||||
source image.Image
|
||||
bounds image.Rectangle
|
||||
offset image.Point
|
||||
}
|
||||
|
||||
func (i croppedImage) ColorModel() color.Model { return i.source.ColorModel() }
|
||||
func (i croppedImage) Bounds() image.Rectangle { return i.bounds }
|
||||
func (i croppedImage) At(x, y int) color.Color {
|
||||
return i.source.At(i.offset.X+x, i.offset.Y+y)
|
||||
}
|
||||
|
||||
func resizeContext(ctx context.Context, source image.Image, width, height int) (*image.NRGBA, error) {
|
||||
bounds := source.Bounds()
|
||||
if bounds.Dx() == width && bounds.Dy() == height {
|
||||
return copyNRGBAContext(ctx, source)
|
||||
}
|
||||
output := image.NewNRGBA(image.Rect(0, 0, width, height))
|
||||
for y := 0; y < height; y++ {
|
||||
if err := contextError(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
y0, y1, fy := sampleCoordinate(y, height, bounds.Dy())
|
||||
for x := 0; x < width; x++ {
|
||||
if x&255 == 0 {
|
||||
if err := contextError(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
x0, x1, fx := sampleCoordinate(x, width, bounds.Dx())
|
||||
c00 := color.NRGBAModel.Convert(source.At(bounds.Min.X+x0, bounds.Min.Y+y0)).(color.NRGBA)
|
||||
c10 := color.NRGBAModel.Convert(source.At(bounds.Min.X+x1, bounds.Min.Y+y0)).(color.NRGBA)
|
||||
c01 := color.NRGBAModel.Convert(source.At(bounds.Min.X+x0, bounds.Min.Y+y1)).(color.NRGBA)
|
||||
c11 := color.NRGBAModel.Convert(source.At(bounds.Min.X+x1, bounds.Min.Y+y1)).(color.NRGBA)
|
||||
output.SetNRGBA(x, y, interpolate(c00, c10, c01, c11, fx, fy))
|
||||
}
|
||||
}
|
||||
return output, nil
|
||||
}
|
||||
|
||||
func sampleCoordinate(destination, destinationSize, sourceSize int) (int, int, uint32) {
|
||||
coordinate := ((int64(2*destination+1)*int64(sourceSize))<<15)/int64(destinationSize) - 1<<15
|
||||
if coordinate <= 0 {
|
||||
return 0, min(1, sourceSize-1), 0
|
||||
}
|
||||
maximum := int64(sourceSize-1) << 16
|
||||
if coordinate >= maximum {
|
||||
return sourceSize - 1, sourceSize - 1, 0
|
||||
}
|
||||
first := int(coordinate >> 16)
|
||||
return first, first + 1, uint32(coordinate & 0xffff)
|
||||
}
|
||||
|
||||
func interpolate(c00, c10, c01, c11 color.NRGBA, fx, fy uint32) color.NRGBA {
|
||||
return color.NRGBA{
|
||||
R: interpolateChannel(c00.R, c10.R, c01.R, c11.R, fx, fy),
|
||||
G: interpolateChannel(c00.G, c10.G, c01.G, c11.G, fx, fy),
|
||||
B: interpolateChannel(c00.B, c10.B, c01.B, c11.B, fx, fy),
|
||||
A: interpolateChannel(c00.A, c10.A, c01.A, c11.A, fx, fy),
|
||||
}
|
||||
}
|
||||
|
||||
func interpolateChannel(c00, c10, c01, c11 uint8, fx, fy uint32) uint8 {
|
||||
const one uint64 = 1 << 16
|
||||
top := uint64(c00)*(one-uint64(fx)) + uint64(c10)*uint64(fx)
|
||||
bottom := uint64(c01)*(one-uint64(fx)) + uint64(c11)*uint64(fx)
|
||||
value := top*(one-uint64(fy)) + bottom*uint64(fy)
|
||||
return uint8((value + 1<<31) >> 32)
|
||||
}
|
||||
|
||||
func copyNRGBAContext(ctx context.Context, source image.Image) (*image.NRGBA, error) {
|
||||
bounds := source.Bounds()
|
||||
output := image.NewNRGBA(image.Rect(0, 0, bounds.Dx(), bounds.Dy()))
|
||||
for y := 0; y < bounds.Dy(); y++ {
|
||||
if err := contextError(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for x := 0; x < bounds.Dx(); x++ {
|
||||
if x&255 == 0 {
|
||||
if err := contextError(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
output.Set(x, y, source.At(bounds.Min.X+x, bounds.Min.Y+y))
|
||||
}
|
||||
}
|
||||
return output, nil
|
||||
}
|
||||
Reference in New Issue
Block a user