package imagefile import ( "bytes" "context" "crypto/sha256" "encoding/hex" "image" "image/color" "image/jpeg" "image/png" "os" "testing" "time" ) func TestActualVariantsHonorDimensionsAlphaAndEXIF(t *testing.T) { if os.Getenv("RUN_VARIANT_TESTS") != "1" { t.Skip("requires actual ImageMagick runtime") } for _, c := range []struct { name string w, h int orientation bool }{{"landscape", 320, 200, false}, {"tiny", 1, 1, false}, {"portrait", 23, 67, false}, {"exif", 40, 20, true}} { t.Run(c.name, func(t *testing.T) { img := image.NewNRGBA(image.Rect(0, 0, c.w, c.h)) img.Set(0, 0, color.NRGBA{R: 255, A: 0}) var encoded bytes.Buffer if c.orientation { if e := jpeg.Encode(&encoded, img, &jpeg.Options{Quality: 82}); e != nil { t.Fatal(e) } } else { if e := png.Encode(&encoded, img); e != nil { t.Fatal(e) } } input := encoded.Bytes() if c.orientation { payload := []byte{'E', 'x', 'i', 'f', 0, 0, 'I', 'I', 42, 0, 8, 0, 0, 0, 1, 0, 18, 1, 3, 0, 1, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0} marker := append([]byte{255, 225, 0, byte(len(payload) + 2)}, payload...) input = append(append(append([]byte{}, input[:2]...), marker...), input[2:]...) } ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() variants, e := NewTransformer().Transform(ctx, bytes.NewReader(input)) if e != nil { t.Fatal(e) } if len(variants) != 3 { t.Fatalf("want three variants, got %d", len(variants)) } w, h := c.w, c.h if c.orientation { w, h = h, w } for _, v := range variants { s := sha256.Sum256(v.Bytes) if v.Metadata.SHA256 != hex.EncodeToString(s[:]) || v.Metadata.SizeBytes != int64(len(v.Bytes)) { t.Fatal("content digest/size mismatch") } wantW, wantH := w, h if v.Metadata.Name == "thumbnail" { wantW, wantH = FitDimensions(w, h, 256) } if v.Metadata.Name == "crop" { wantW, wantH = 128, 128 } if v.Metadata.Width != wantW || v.Metadata.Height != wantH { t.Fatalf("%s: got %dx%d want %dx%d", v.Metadata.Name, v.Metadata.Width, v.Metadata.Height, wantW, wantH) } if v.Metadata.ContentType == "image/jpeg" { decoded, e := jpeg.Decode(bytes.NewReader(v.Bytes)) if e != nil { t.Fatal(e) } if decoded.Bounds().Dx() != wantW || decoded.Bounds().Dy() != wantH { t.Fatal("actual JPEG geometry mismatch") } if !c.orientation { r, g, b, _ := decoded.At(0, 0).RGBA() if r < 64000 || g < 64000 || b < 64000 { t.Fatal("alpha was not composited on white") } } } else if len(v.Bytes) < 16 || string(v.Bytes[:4]) != "RIFF" || string(v.Bytes[8:12]) != "WEBP" { t.Fatal("optimized file is not WebP") } } }) } }