Backtestshugorun-20260917-015623#12543

Issue #12543 Merged fix PR # Run 17 Sep 2026 · run-20260917-015623 gohugoio/hugo

resources/images: Poor overlay quality when background image is an indexed (not true color) PNG

Better

Our patch was judged better than the merged fix.

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

Both patches fix the reported root cause identically: they stop re-quantizing the filtered result back onto the source's indexed palette by gating the `conf.TargetFormat == images.PNG` palette re-application on the action type. For issue 12543 the core correctness is equivalent — the offending code path is the `paletted` re-application after Overlay/Text, and both skip it for the filter action. Both also update the same two relevant golden fixtures (overlay.png, text.png), so the direct test evidence for THIS issue is a wash.

The decision turns on scope and robustness. Patch A is minimal and focused: one gated condition reusing the existing `images.Actions` whitelist (resize/crop/fit/fill), with a clear comment explaining that only geometric transforms preserve the source's colors while filters legitimately introduce new ones. The whitelist is also slightly more robust than Patch B's blacklist — any future non-geometric action defaults to NOT re-quantizing (the safe behavior), whereas Patch B's `conf.Action != images.ActionFilter` would wrongly re-apply the palette to any new filter-like action not literally named "filter".

Patch B, by contrast, bundles a substantial and unrelated fix for a different issue (12536, NRGBA/alpha-premultiplication in hex color handling): it rewrites Color.init, ColorGoToHexString, AddColorToPalette, and hexStringToColorGo, adds an ActionFilter constant, and touches a third golden file (padding-transparent-chained.png) plus new color_test.go cases. Those color changes are genuine improvements, but none of them are on the indexed-PNG-overlay path, and the diff itself cites "issue 12536" for them. Per the scope criterion, this unrelated bug fix and its tests count against B for a review scoped to 12543. With correctness and issue-specific tests essentially tied, Patch A's tighter scope and marginally safer whitelist logic make it the better fix for the reported issue.

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

19m 28s3 turns

Wall-clock time in the container

Full test suite

No new failures

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

Contamination audit

Unknown

See the audit notes for this run

Patch size

8vs 58 merged

Changed lines, ours vs merged

Reference: <https://discourse.gohugo.io/t/image-overlay-quality-is-poor/50034>

Before getting into the details, I have verified that this is not an upstream issue with disintegration/gift. I tested with this:

<details>
<summary>main.go</summary>

package main

import (
	"image"
	"image/png"
	"log"
	"os"

	_ "image/png"

	"github.com/disintegration/gift"
)

func main() {
	// Get the background image (24 bit: indexed not true color)
	f, err := os.Open("background.png")
	if err != nil {
		log.Fatal(err)
	}
	bgImage, _, err := image.Decode(f)
	if err != nil {
		log.Fatal(err)
	}

	// Get the foreground image (24 bit with 8 bit alpha channel)
	f, err = os.Open("foreground.png")
	if err != nil {
		log.Fatal(err)
	}
	fgImage, _, err := image.Decode(f)
	if err != nil {
		log.Fatal(err)
	}

	// Create a new image with dimensions of the bgImage.
	dstImage := image.NewRGBA(bgImage.Bounds())
	// Copy the bgImage to the dstImage.
	gift.New().Draw(dstImage, bgImage)
	// Draw the fgImage over the dstImage at the (20, 20) position.
	gift.New().DrawAt(dstImage, fgImage, image.Pt(20, 20), gift.OverOperator)

	// Create the composite file.
	f, err = os.Create("composite.png")
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()

	// Encode the composite image.
	err = png.Encode(f, dstImage)
	if err != nil {
		log.Fatal(err)
	}
}

</details>

Details:

  • Background image is a 24 bit indexed PNG file with 256 colors in its palette
  • Foreground image is a 24 bit true color PNG with an 8 bit alpha channel
  • The final (composite) image seems to be limited to the palette of the background image

Simple example:

git clone --single-branch -b hugo-github-issue-12543 https://github.com/jmooring/hugo-testing hugo-github-issue-12543
cd hugo-github-issue-12543
hugo server

Note that GIF images (also indexed) work fine.

The two patches

Our patch+7 −1
resources/image.goindex 467e23f26..6db4a018a 100644@@ -438,7 +438,13 @@ func (i *imageResource) doWithImageConfig(conf images.ImageConfig, f func(src im 			converted = tmp 		} -		if conf.TargetFormat == images.PNG {+		// Re-apply the source's palette only for the geometric transforms+		// (resize/crop/fit/fill), which preserve the image's own colours and+		// benefit from keeping the smaller indexed PNG. Filters such as Overlay+		// and Text can introduce colours outside the source palette, and+		// quantizing the result back onto that palette degrades quality.+		// See https://github.com/gohugoio/hugo/issues/12543.+		if conf.TargetFormat == images.PNG && images.Actions[conf.Action] { 			// Apply the colour palette from the source 			if paletted, ok := src.(*image.Paletted); ok { 				palette := paletted.Paletteresources/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 
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

Summary

What was wrong

Hugo issue #12543: overlaying (or adding text to) an indexed/paletted PNG background produced a low-quality composite because the output was clamped to the background's 256-color palette. GIF (also indexed) was unaffected.

The cause was in resources/image.go, doWithImageConfig. After the image was processed (the overlay/text composite is correctly built as a full-color NRGBA image), a post-processing block re-quantized the finished composite back onto the source PNG's palette whenever the target format was PNG and the source decoded as *image.Paletted:

if conf.TargetFormat == images.PNG {
    if paletted, ok := src.(*image.Paletted); ok {
        tmp := image.NewPaletted(converted.Bounds(), palette)
        draw.FloydSteinberg.Draw(tmp, tmp.Bounds(), converted, ...)
        converted = tmp
    }
}

This is fine for geometric transforms (resize/crop/fit/fill), which only rescale the image's own colors and benefit from a small indexed PNG. But for .Filter operations like Overlay/Text — which composite new colors not in the source palette — Floyd–Steinberg dithering onto that 256-color palette destroys quality. It was PNG-only, which is why GIF worked.

What I changed

Guarded the palette re-application so it runs only for geometric-transform actions, using the existing exported images.Actions map (contains only resize/crop/fit/fill):

if conf.TargetFormat == images.PNG && images.Actions[conf.Action] {

.Filter sets conf.Action == "filter" (not in the map), so overlay/text now keep the full-color composite; resize/crop/fit/fill behavior is unchanged. This is a one-condition change (resources/image.go, +7/−1 including an explanatory comment).

I also regenerated the two pre-fix baseline golden files for this issue — resources/images/testdata/images_golden/filters/paletted/overlay.png and text.png (committed in 62e24b7ed with the note "before any fix is applied"). They changed from indexed (PNG color-type 03) to truecolor (color-type 02), confirming the composite is no longer palette-clamped.

Test evidence

  • Reproduce: with buggy code, TestImagesGoldenFiltersPaletted passed against the pre-fix (indexed) goldens.
  • Fix effective: with the code fix but the old goldens, the same test failed (golden mismatch) — proving the output changed.
  • Goldens regenerated & verified: new overlay.png/text.png are color-type 02 (truecolor); reviewer visually confirmed smooth gradients / crisp text with no dithering banding.
  • Gate (green) — go test ./resources/ ./resources/images/ ./tpl/images/ (amd64, in the project container): ok github.com/gohugoio/hugo/resources 5.234s ok github.com/gohugoio/hugo/resources/images 30.802s (all golden tests, incl. paletted, methods, process, mask, padding, webp, avif) ok github.com/gohugoio/hugo/tpl/images 0.624s The regression test passes, and no previously passing test regressed. Geometric-transform golden files (indexed gopher resize/crop) are unchanged, as intended.

No existing test was modified, skipped, weakened, or deleted. All changes are left uncommitted in the working tree. (The AGENTS.md/CLAUDE.md deletions in git status are pre-existing environment state, not part of this fix.)