search for white index

This commit is contained in:
Júlio César Batista 2023-04-28 18:53:29 -03:00
parent 129d51a1e6
commit 56af2f41e3
No known key found for this signature in database
GPG key ID: 10C4B861BF314878
2 changed files with 21 additions and 3 deletions

Binary file not shown.

Before

Width:  |  Height:  |  Size: 219 KiB

After

Width:  |  Height:  |  Size: 207 KiB

View file

@ -62,7 +62,7 @@ func AnimatePNGs(ms *xmain.State, pngs [][]byte, animIntervalMs int) ([]byte, er
// 1. convert the PNG into a GIF compatible image (Bitmap) by quantizing it to 255 colors // 1. convert the PNG into a GIF compatible image (Bitmap) by quantizing it to 255 colors
buf := bytes.NewBuffer(nil) buf := bytes.NewBuffer(nil)
err := gif.Encode(buf, pngImage, &gif.Options{ err := gif.Encode(buf, pngImage, &gif.Options{
NumColors: 255, // GIFs can have up to 256 colors, so keep 1 slot for white background NumColors: 256, // GIFs can have up to 256 colors
Quantizer: quantize.MedianCutQuantizer{}, Quantizer: quantize.MedianCutQuantizer{},
}) })
if err != nil { if err != nil {
@ -86,8 +86,8 @@ func AnimatePNGs(ms *xmain.State, pngs [][]byte, animIntervalMs int) ([]byte, er
var bgIndex int var bgIndex int
if len(palettedImg.Palette) == 256 { if len(palettedImg.Palette) == 256 {
bgIndex = 255 bgIndex = findWhiteIndex(palettedImg.Palette)
palettedImg.Palette[255] = BG_COLOR palettedImg.Palette[bgIndex] = BG_COLOR
} else { } else {
bgIndex = len(palettedImg.Palette) bgIndex = len(palettedImg.Palette)
palettedImg.Palette = append(palettedImg.Palette, BG_COLOR) palettedImg.Palette = append(palettedImg.Palette, BG_COLOR)
@ -115,6 +115,24 @@ func AnimatePNGs(ms *xmain.State, pngs [][]byte, animIntervalMs int) ([]byte, er
return buf.Bytes(), nil return buf.Bytes(), nil
} }
func findWhiteIndex(palette color.Palette) int {
nearestIndex := 0
nearestScore := 0.
for i, c := range palette {
r, g, b, _ := c.RGBA()
if r == 255 && g == 255 && b == 255 {
return i
}
avg := float64(r+g+b) / 255.
if avg > nearestScore {
nearestScore = avg
nearestIndex = i
}
}
return nearestIndex
}
func Validate(gifBytes []byte, nFrames int, intervalMS int) error { func Validate(gifBytes []byte, nFrames int, intervalMS int) error {
anim, err := gif.DecodeAll(bytes.NewBuffer(gifBytes)) anim, err := gif.DecodeAll(bytes.NewBuffer(gifBytes))
if err != nil { if err != nil {