Fill transparent areas with white in JPEG output (closes #362) #373

Merged
clawbot merged 2 commits from issue-362-jpeg-white-background into next 2026-11-19 07:55:14 +01:00
3 changed files with 164 additions and 2 deletions

No files matched your search

+4
View File
@@ -549,6 +549,10 @@ example.
PNG or JPEG XL source. This holds in every output format, `orig` included. So an
animated GIF requested as GIF comes back as a still GIF.
**Transparency.** JPEG has no transparency, so pixa fills the transparent areas
of an image with white in JPEG output. This applies to `auto` too, when it
chooses JPEG.
**SVG sources.** `orig` of an SVG source is the SVG itself, unchanged, and is
cached like any other image. It is given only at the `orig` size, since pixa
does not resize an SVG as SVG. `orig` of an SVG at any other size is refused
+13 -2
View File
@@ -808,9 +808,20 @@ func (p *ImageProcessor) encode(
// every setting whose zero value is not what pixa wants. Stripping metadata
// drops EXIF, XMP, IPTC and the ICC profile.
// exportJPEG encodes img as JPEG at quality, without metadata. The settings
// it leaves out are at libvips' defaults.
// exportJPEG encodes img as JPEG at quality, without metadata. JPEG has no
// transparency, so any transparent areas are filled with white; left to
// itself, libvips would fill them with black. govips scales the 8-bit white
// for a 16-bit image. The settings it leaves out are at libvips' defaults.
func exportJPEG(img *vips.ImageRef, quality int) ([]byte, error) {
if img.HasAlpha() {
err := img.Flatten(&vips.Color{
R: math.MaxUint8, G: math.MaxUint8, B: math.MaxUint8,
})
if err != nil {
return nil, fmt.Errorf("failed to fill transparent areas: %w", err)
}
}
output, _, err := img.ExportJpeg(&vips.JpegExportParams{
StripMetadata: true,
Quality: quality,
@@ -0,0 +1,147 @@
package imageprocessor
import (
"bytes"
"image"
"image/color"
"image/jpeg"
"image/png"
"testing"
"github.com/davidbyttow/govips/v2/vips"
"sneak.berlin/go/pixa/internal/imagerequest"
)
// createHalfTransparentPNG creates a PNG whose left half is fully transparent
// and whose right half is opaque red, 8 or 16 bits per sample.
func createHalfTransparentPNG(t *testing.T, sixteenBit bool) []byte {
t.Helper()
const width, height = 40, 20
var img image.Image
red := color.NRGBA{R: 255, A: 255}
if sixteenBit {
rgba := image.NewNRGBA64(image.Rect(0, 0, width, height))
for y := range height {
for x := width / 2; x < width; x++ {
rgba.Set(x, y, red)
}
}
img = rgba
} else {
rgba := image.NewNRGBA(image.Rect(0, 0, width, height))
for y := range height {
for x := width / 2; x < width; x++ {
rgba.Set(x, y, red)
}
}
img = rgba
}
var buf bytes.Buffer
err := png.Encode(&buf, img)
if err != nil {
t.Fatalf("failed to encode test PNG: %v", err)
}
return buf.Bytes()
}
// createHalfTransparentGreyPNG creates a grey PNG with an alpha channel,
// two bands, whose left half is fully transparent and whose right half is
// opaque. Go's PNG encoder cannot write grey with alpha, so libvips does.
func createHalfTransparentGreyPNG(t *testing.T) []byte {
t.Helper()
img, err := vips.NewImageFromBuffer(createHalfTransparentPNG(t, false))
if err != nil {
t.Fatalf("failed to decode test PNG: %v", err)
}
defer img.Close()
err = img.ToColorSpace(vips.InterpretationBW)
if err != nil {
t.Fatalf("failed to convert test PNG to grey: %v", err)
}
if img.Bands() != 2 {
t.Fatalf("grey test image has %d bands, want 2", img.Bands())
}
output, _, err := img.ExportPng(&vips.PngExportParams{
Compression: pngCompression,
Filter: vips.PngFilterNone,
})
if err != nil {
t.Fatalf("failed to save grey test PNG: %v", err)
}
return output
}
// TestImageProcessor_JPEGFillsTransparencyWithWhite verifies that the
// transparent areas of a source become white in JPEG output, for 8-bit,
// 16-bit and grey sources with an alpha channel.
func TestImageProcessor_JPEGFillsTransparencyWithWhite(t *testing.T) {
t.Parallel()
tests := []struct {
name string
input func(t *testing.T) []byte
}{
{"8-bit RGBA", func(t *testing.T) []byte {
t.Helper()
return createHalfTransparentPNG(t, false)
}},
{"16-bit RGBA", func(t *testing.T) []byte {
t.Helper()
return createHalfTransparentPNG(t, true)
}},
{"grey with alpha", createHalfTransparentGreyPNG},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
result, err := New(Params{
MaxInputBytes: 50 << 20,
MaxConcurrentProcessing: 1,
}).Process(
t.Context(), bytes.NewReader(tt.input(t)),
imagerequest.FormatPNG,
&imagerequest.Transform{Format: imagerequest.FormatJPEG},
)
if err != nil {
t.Fatalf("Process() error = %v", err)
}
defer func() { _ = result.Content.Close() }()
decoded, err := jpeg.Decode(result.Content)
if err != nil {
t.Fatalf("failed to decode JPEG output: %v", err)
}
r, g, b, _ := decoded.At(5, 10).RGBA()
t.Logf("transparent area came out as %d,%d,%d",
r>>8, g>>8, b>>8)
// JPEG is lossy, so white is any value close to 255
const nearWhite = 250
if r>>8 < nearWhite || g>>8 < nearWhite || b>>8 < nearWhite {
t.Errorf("transparent area = %d,%d,%d, want white",
r>>8, g>>8, b>>8)
}
})
}
}