Backtestshugorun-20260930-140149#12536

Issue #12536 Merged fix PR # Run 30 Sep 2026 · run-20260930-140149 gohugoio/hugo

images: Opacity problem with Resize + Padding with PNG output

Worse

The merged fix was judged better than our patch.

In this judgment, Patch B = our agent, Patch A = the merged fix.

Patch A fixes the likely root causes. First, hex colors with alpha were parsed as premultiplied `color.RGBA`, so a transparent padding color had components greater than alpha. That is an invalid color, and it gets corrupted when drawn. A parses hex as `color.NRGBA` and normalizes the hex/luminance code to match. Second, the source palette was clamped back onto the output after filters ran. Since Padding runs through `Filter`, the transparent padding was lost when the result went back to the original indexed palette. A skips palette re-application for the filter action. It also makes `AddColorToPalette` compare by color value, so NRGBA and RGBA versions of the same color match. It updates the hex parsing and formatting unit tests with transparent cases that would fail before the change, and regenerates golden images, including `padding-transparent-chained`. Patch B only adds a hard-to-read condition around palette application, based on `bgColor`, `hasAlpha` and `IsOpaque(src)`. It leaves the invalid premultiplied color parsing untouched, adds no tests, and its logic is fragile: the palette is still applied whenever `bgColor` is set, and it is unclear whether it covers the Padding case at all. A's broader change (filters no longer clamp to the source palette) adds some risk, but it is justified and reflected in the updated golden files.

The judge saw only the two patches, labelled A and B in random order, with issue links and version numbers removed. The reasoning above is shown verbatim.

Solve

5m 53s16 turns

Wall-clock time in the container

Full test suite

No new failures

3,751 passed · 99 skipped · 3,852 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

5vs 58 merged

Changed lines, ours vs merged

What version of Hugo are you using (hugo version)?

$ hugo version
hugo v0.126.1+extended linux/amd64

Does this issue reproduce with the latest release?

Yes.

Report

The 0 function currently ignores the transparency setting when padding a PNG image. While the documentation does state 'conversion to WEBP is required to support transparency' (under Other recipes), I can't see a reason why PNG shouldn't be supported, given that it has an alpha channel. For the moment I have resorted to first converting the image to WEBP, then applying transparent padding, and then converting it back to PNG, but this does not feel like an elegant solution.

The two patches

Our patch+3 −2
resources/image.goindex 467e23f26..a7f935fee 100644@@ -439,8 +439,9 @@ func (i *imageResource) doWithImageConfig(conf images.ImageConfig, f func(src im 		}  		if conf.TargetFormat == images.PNG {-			// Apply the colour palette from the source-			if paletted, ok := src.(*image.Paletted); ok {+			// Apply the colour palette from the source, unless processing+			// added transparency that an opaque source palette cannot represent.+			if paletted, ok := src.(*image.Paletted); ok && (bgColor != nil || !hasAlpha || !images.IsOpaque(src)) { 				palette := paletted.Palette 				if bgColor != nil && len(palette) < 256 { 					palette = images.AddColorToPalette(bgColor, palette) 
Merged fix · PR #+39 −19
resources/image.goindex 467e23f26..a2ed5f3c9 100644@@ -321,7 +321,7 @@ func (i *imageResource) Filter(filters ...any) (images.ImageResource, error) { 		return nil, err 	} -	confMain.Action = "filter"+	confMain.Action = images.ActionFilter 	confMain.Key = hashing.HashString(gfilters)  	return i.doWithImageConfig(confMain, func(src image.Image) (image.Image, error) {@@ -438,7 +438,11 @@ func (i *imageResource) doWithImageConfig(conf images.ImageConfig, f func(src im 			converted = tmp 		} -		if conf.TargetFormat == images.PNG {+		// Preserve the source palette for the geometric actions so an indexed+		// PNG stays indexed. Filters (e.g. images.Overlay, images.Text) routinely+		// introduce colors outside the source palette, and clamping the result+		// back to that palette destroys the filtered output. See issue 12543.+		if conf.TargetFormat == images.PNG && conf.Action != images.ActionFilter { 			// Apply the colour palette from the source 			if paletted, ok := src.(*image.Paletted); ok { 				palette := paletted.Paletteresources/images/color.goindex fe233c7b7..72f3710e3 100644@@ -69,9 +69,12 @@ func (c Color) Key() string { }  func (c *Color) init() error {-	c.hex = ColorGoToHexString(c.color)-	r, g, b, _ := c.color.RGBA()-	c.luminance = 0.2126*c.toSRGB(uint8(r)) + 0.7152*c.toSRGB(uint8(g)) + 0.0722*c.toSRGB(uint8(b))+	// Normalize to the canonical non-premultiplied form so that equal colors+	// compare equal whether they came from a hex string or from image pixels.+	nrgba := color.NRGBAModel.Convert(c.color).(color.NRGBA)+	c.color = nrgba+	c.hex = ColorGoToHexString(nrgba)+	c.luminance = 0.2126*c.toSRGB(nrgba.R) + 0.7152*c.toSRGB(nrgba.G) + 0.0722*c.toSRGB(nrgba.B) 	return nil } @@ -88,10 +91,13 @@ func (c Color) toSRGB(i uint8) float64 { // Note that it does no additional checks, so callers must make sure // that the palette is valid for the relevant format. func AddColorToPalette(c color.Color, p color.Palette) color.Palette {-	var found bool-	if slices.Contains(p, c) {-		found = true-	}+	// Compare color values rather than interface values, so that e.g. a+	// color.NRGBA is found even if the palette holds it as a color.RGBA.+	cr, cg, cb, ca := c.RGBA()+	found := slices.ContainsFunc(p, func(v color.Color) bool {+		vr, vg, vb, va := v.RGBA()+		return cr == vr && cg == vg && cb == vb && ca == va+	})  	if !found { 		p = append(color.Palette{c}, p...)@@ -108,12 +114,13 @@ func ReplaceColorInPalette(c color.Color, p color.Palette) {  // ColorGoToHexString converts a color.Color to a hex string. func ColorGoToHexString(c color.Color) string {-	r, g, b, a := c.RGBA()-	rgba := color.RGBA{uint8(r), uint8(g), uint8(b), uint8(a)}-	if rgba.A == 0xff {-		return fmt.Sprintf("#%.2x%.2x%.2x", rgba.R, rgba.G, rgba.B)+	// Hex notation is not alpha-premultiplied, so convert via NRGBA to+	// un-premultiply the color components of any transparent color.+	nrgba := color.NRGBAModel.Convert(c).(color.NRGBA)+	if nrgba.A == 0xff {+		return fmt.Sprintf("#%.2x%.2x%.2x", nrgba.R, nrgba.G, nrgba.B) 	}-	return fmt.Sprintf("#%.2x%.2x%.2x%.2x", rgba.R, rgba.G, rgba.B, rgba.A)+	return fmt.Sprintf("#%.2x%.2x%.2x%.2x", nrgba.R, nrgba.G, nrgba.B, nrgba.A) }  // ColorGoToColor converts a color.Color to a Color.@@ -195,5 +202,8 @@ func hexStringToColorGo(s string) (color.Color, error) { 		return nil, err 	} -	return color.RGBA{b[0], b[1], b[2], b[3]}, nil+	// Hex notation is not alpha-premultiplied, so this must be a color.NRGBA;+	// as a color.RGBA any transparent color would be invalid (component > alpha)+	// and corrupted when drawn onto an alpha-premultiplied image. See issue 12536.+	return color.NRGBA{b[0], b[1], b[2], b[3]}, nil }resources/images/color_test.goindex 540f3bea8..47bc5ae8b 100644@@ -39,8 +39,12 @@ func TestHexStringToColor(t *testing.T) { 		{"#ffffff", color.White}, 		{"ffffff", color.White}, 		{"#000", color.Black},-		{"#4287f5", color.RGBA{R: 0x42, G: 0x87, B: 0xf5, A: 0xff}},-		{"777", color.RGBA{R: 0x77, G: 0x77, B: 0x77, A: 0xff}},+		{"#4287f5", color.NRGBA{R: 0x42, G: 0x87, B: 0xf5, A: 0xff}},+		{"777", color.NRGBA{R: 0x77, G: 0x77, B: 0x77, A: 0xff}},+		// Hex notation is not alpha-premultiplied, so a transparent color+		// must parse to a color.NRGBA. See issue 12536.+		{"#00f7", color.NRGBA{R: 0x00, G: 0x00, B: 0xff, A: 0x77}},+		{"4287f580", color.NRGBA{R: 0x42, G: 0x87, B: 0xf5, A: 0x80}}, 	} {  		c.Run(test.arg, func(c *qt.C) {@@ -71,10 +75,11 @@ func TestColorToHexString(t *testing.T) { 		{color.Black, "#000000"}, 		{color.RGBA{R: 0x42, G: 0x87, B: 0xf5, A: 0xff}, "#4287f5"}, -		// 50% opacity.+		// 50% opacity. Hex notation is not alpha-premultiplied, so the+		// components of a transparent color are the non-premultiplied ones. 		// Note that the .Colors (dominant colors) received from the Image resource 		// will always have an alpha value of 0xff.-		{color.RGBA{R: 0x42, G: 0x87, B: 0xf5, A: 0x80}, "#4287f580"},+		{color.NRGBA{R: 0x42, G: 0x87, B: 0xf5, A: 0x80}, "#4287f580"}, 	} {  		c.Run(test.expect, func(c *qt.C) {resources/images/config.goindex 4cbd7e629..e8fd69c94 100644@@ -36,6 +36,7 @@ const ( 	ActionCrop   = "crop" 	ActionFit    = "fit" 	ActionFill   = "fill"+	ActionFilter = "filter" )  var Actions = map[string]bool{resources/images/testdata/images_golden/filters/padding/padding-transparent-chained.pngindex 899e21f25..34392755c 100644Binary files a/resources/images/testdata/images_golden/filters/padding/padding-transparent-chained.png and b/resources/images/testdata/images_golden/filters/padding/padding-transparent-chained.png differresources/images/testdata/images_golden/filters/paletted/overlay.pngindex 10d9dd6fd..631854dd8 100644Binary files a/resources/images/testdata/images_golden/filters/paletted/overlay.png and b/resources/images/testdata/images_golden/filters/paletted/overlay.png differresources/images/testdata/images_golden/filters/paletted/text.pngindex 71a9c3e2d..65d1a60ce 100644Binary files a/resources/images/testdata/images_golden/filters/paletted/text.png and b/resources/images/testdata/images_golden/filters/paletted/text.png differ 

What the agent reported

I've made a fix, but none of it has been built or tested. There's no Go module cache and no network access here, so ./bt-test ./resources/images/ -run TestImagesPaddingTransparentPNG failed at setup ([setup failed], downloads from proxy.golang.org refused). Plain go vet failed the same way. No Go test in this repo can run in this environment.

What was wrong: When the output is PNG and the source is an indexed PNG (a PNG with a fixed palette of up to 256 colours), doWithImageConfig redraws the processed result using the source's palette (resources/image.go, ~line 441). gohugoio8.png has 256 colours, all fully opaque. I checked that with a small standard-library-only Go program, since the repo can't build. So the transparent padding from images.Padding 20 "#0000" was snapped to the nearest opaque colour. "Resize then Padding" hits this every time: resizing an indexed PNG to PNG gives another indexed PNG, which the padding step then decodes. WEBP output never goes through this step, which is why the WEBP workaround worked.

What I changed: one condition in resources/image.go:

// Apply the colour palette from the source, unless processing
// added transparency that an opaque source palette cannot represent.
if paletted, ok := src.(*image.Paletted); ok && (bgColor != nil || !hasAlpha || !images.IsOpaque(src)) {

The source palette is now skipped only when all three hold: no background fill was applied, the result has transparency, and the source is fully opaque. In that case the PNG is written as a full-colour image with its transparency intact.

What else this affects: Only PNG output from an opaque indexed source whose processed result has transparency and no background fill. The old output was wrong in the same way. Other filters that add transparency to such a PNG (e.g. a mask) will now also keep it, and those files will be larger than before. Everything else is unchanged:

  • Opaque results: the palette is still applied. The TestImagesGoldenFiltersPaletted overlay and text outputs are opaque, so their golden images shouldn't change.
  • Indexed sources that already have transparency (like gopher-hero8.png): unchanged.
  • Background-fill cases: unchanged.
  • Other output formats: unaffected, including the gohugoio8.png→AVIF golden test.

The reviewer agent reached the same conclusions from the code, and gofmt passes.

About the test: I wrote a regression test, but I've taken it out of the diff because I could never see it fail before the fix or pass after it. So the diff now has no test, which breaks the "must include a test" rule. With no way to run tests here, I couldn't meet both rules and chose not to ship an unrun test. To restore it, add it to resources/images/images_integration_test.go (imports image/png, strings, qt "github.com/frankban/quicktest") and run it once modules are available:

func TestImagesPaddingTransparentPNGFromPaletted(t *testing.T) {
	t.Parallel()
	files := `
-- hugo.toml --
-- assets/gohugoio8.png --
sourcefilename: ../testdata/gohugoio8.png
-- layouts/home.html --
{{ $r := (resources.Get "gohugoio8.png").Resize "200x png" }}
{{ ($r.Filter (images.Padding 20 "#0000") | resources.Copy "images/chained.png").Publish }}
{{ ((resources.Get "gohugoio8.png").Filter (images.Process "resize 200x png") (images.Padding 20 "#0000") | resources.Copy "images/onepass.png").Publish }}
{{ ((resources.Get "gohugoio8.png").Filter (images.Padding 20 "#0000") | resources.Copy "images/direct.png").Publish }}
`
	b := hugolib.Test(t, files)
	for _, test := range []struct {
		filename      string
		width, height int
	}{
		{"public/images/chained.png", 240, 140},
		{"public/images/onepass.png", 240, 140},
		{"public/images/direct.png", 940, 490},
	} {
		img, err := png.Decode(strings.NewReader(b.FileContent(test.filename)))
		b.Assert(err, qt.IsNil, qt.Commentf("%s", test.filename))
		bounds := img.Bounds()
		b.Assert(bounds.Dx(), qt.Equals, test.width, qt.Commentf("%s", test.filename))
		b.Assert(bounds.Dy(), qt.Equals, test.height, qt.Commentf("%s", test.filename))
		_, _, _, a := img.At(bounds.Min.X, bounds.Min.Y).RGBA()
		b.Assert(a, qt.Equals, uint32(0), qt.Commentf("%s: padding alpha", test.filename))
		_, _, _, a = img.At(bounds.Min.X+bounds.Dx()/2, bounds.Min.Y+bounds.Dy()/2).RGBA()
		b.Assert(a, qt.Equals, uint32(0xffff), qt.Commentf("%s: center alpha", test.filename))
	}
}

Before the fix, the corner pixel should come out fully opaque instead of transparent, because the source palette has no transparent colour. The goldens and the full ./resources/images/ and ./resources/ packages also need a run once modules are available.

Requirements:

  1. Padding a PNG should keep the transparent colour instead of ignoring it: fixed in code, as explained above; not tested.
  2. Resize followed by Padding with PNG output: covered by the same change; the "chained" and "one-pass" cases in the test above check it. Not run.
  3. No longer need the WEBP → pad → PNG workaround: follows from 1. The docs line saying WEBP is required for transparency now looks out of date, but that's on the separate gohugo.io docs site, so I left it alone.

The AGENTS.md and CLAUDE.md deletions were already in the working tree before I started, and I didn't touch them. Nothing is committed.