diff --git a/encode/encode.go b/encode/encode.go index 4d51332622..4c53da0d36 100644 --- a/encode/encode.go +++ b/encode/encode.go @@ -6,9 +6,11 @@ import ( "fmt" "image" "image/color" + "image/draw" "image/gif" "time" + "github.com/ericpauley/go-quantize/quantize" "github.com/pkg/errors" "github.com/tidbyt/go-libwebp/webp" "github.com/vmihailenco/msgpack/v5" @@ -147,33 +149,9 @@ func (s *Screens) EncodeGIF(filters ...ImageFilter) ([]byte, error) { return nil, fmt.Errorf("image %d is %T, require RGBA", imIdx, im) } - palette := color.Palette{} - idxByColor := map[color.RGBA]int{} - - // Create the palette - for x := 0; x < imRGBA.Bounds().Dx(); x++ { - for y := 0; y < imRGBA.Bounds().Dy(); y++ { - c := imRGBA.RGBAAt(x, y) - if _, found := idxByColor[c]; !found { - idxByColor[c] = len(palette) - palette = append(palette, c) - } - } - } - if len(palette) > 256 { - return nil, fmt.Errorf( - "require <=256 colors, found %d in image %d", - len(palette), imIdx, - ) - } - - // Construct the paletted image + palette := quantize.MedianCutQuantizer{}.Quantize(make([]color.Color, 0, 256), im) imPaletted := image.NewPaletted(imRGBA.Bounds(), palette) - for x := 0; x < imRGBA.Bounds().Dx(); x++ { - for y := 0; y < imRGBA.Bounds().Dy(); y++ { - imPaletted.SetColorIndex(x, y, uint8(idxByColor[imRGBA.RGBAAt(x, y)])) - } - } + draw.Draw(imPaletted, imRGBA.Bounds(), imRGBA, image.Point{0, 0}, draw.Src) g.Image = append(g.Image, imPaletted) g.Delay = append(g.Delay, int(s.delay/10)) // in 100ths of a second diff --git a/go.mod b/go.mod index d0d83a1ddf..5e42f47d80 100644 --- a/go.mod +++ b/go.mod @@ -5,6 +5,7 @@ go 1.16 require ( github.com/antchfx/xmlquery v1.3.11 github.com/dustin/go-humanize v1.0.0 + github.com/ericpauley/go-quantize v0.0.0-20200331213906-ae555eb2afa4 // indirect github.com/fogleman/gg v1.3.0 github.com/fsnotify/fsnotify v1.5.4 github.com/go-playground/validator/v10 v10.11.0 diff --git a/go.sum b/go.sum index 84ef63694f..9aeee206a1 100644 --- a/go.sum +++ b/go.sum @@ -132,6 +132,8 @@ github.com/envoyproxy/go-control-plane v0.9.10-0.20210907150352-cf90f659a021/go. github.com/envoyproxy/go-control-plane v0.10.1/go.mod h1:AY7fTTXNdv/aJ2O5jwpxAPOWUZ7hQAEvzN5Pf27BkQQ= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/envoyproxy/protoc-gen-validate v0.6.2/go.mod h1:2t7qjJNvHPx8IjnBOzl9E9/baC+qXE/TeeyBRzgJDws= +github.com/ericpauley/go-quantize v0.0.0-20200331213906-ae555eb2afa4 h1:BBade+JlV/f7JstZ4pitd4tHhpN+w+6I+LyOS7B4fyU= +github.com/ericpauley/go-quantize v0.0.0-20200331213906-ae555eb2afa4/go.mod h1:H7chHJglrhPPzetLdzBleF8d22WYOv7UM/lEKYiwlKM= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU= github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk=