go-quantize
go-quantize copied to clipboard
Consider prepending the transparency entry in the palette
Hi,
Adding full transparency as the last color means the image defaults to some other, non-transparent color. Presumably, clearing the image first would make it fully transparent, but a nice trick to make a new paletted image transparent before drawing over it with draw.Draw is to make 0th color image.Transparent.
Changing this behavior of quantizer.Quantizer.Quantize might, of course, cause incompatibility in case anyone depended on transparency being the last image, rather than verifying with palette.Index(). If this is a concern, would you consider adding a new config field to quantizer.Quantizer struct?
Right now I'm doing this (g being image/gif.GIF):
quantizer := quantize.MedianCutQuantizer{AddTransparent: false}
palette := color.Palette(make([]color.Color, 1, 256)) // preallocate one space for transparency
palette[0] = image.Transparent
palette = quantizer.Quantize(palette, img) // quantizer.Quantize will only use the remaining space (255 colors)
pal := image.NewPaletted(img.Bounds(), palette)
draw.Draw(pal, img.Bounds(), img, image.ZP, draw.Over)
g.Image = append(g.Image, pal)
g.Delay = append(g.Delay, 50)
g.Disposal = append(g.Disposal, gif.DisposalBackground)
g.BackgroundIndex = 0