Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert image.RGBA (image.Image) to image.Paletted?

I'm trying to create an animated GIF from a series of arbitrary non-paletted images. In order to create a paletted image, I need to come up with a palette somehow.

// RGBA, etc. images from somewhere else
var frames []image.Image

outGif := &gif.GIF{}
for _, simage := range frames {
  // TODO: Convert image to paletted image
  // bounds := simage.Bounds()
  // palettedImage := image.NewPaletted(bounds, ...)

  // Add new frame to animated GIF
  outGif.Image = append(outGif.Image, palettedImage)
  outGif.Delay = append(outGif.Delay, 0)
}
gif.EncodeAll(w, outGif)

Is there an easy way in golang stdlib to accomplish this?

like image 875
Taylor Hughes Avatar asked Mar 07 '16 18:03

Taylor Hughes


2 Answers

It seems an automatic way of intelligently generating palettes is missing from the golang stdlib (correct me if I'm wrong here). But there seems to be a stub for providing your own Quantizer, which led me to the gogif project. (Which was the apparent source of image.Gif.)

I was able to borrow the MedianCutQuantizer from that project, defined here:

https://github.com/andybons/gogif/blob/master/mediancut.go

Which results in the following:

var subimages []image.Image // RGBA, etc. images from somewhere else

outGif := &gif.GIF{}
for _, simage := range subimages {
  bounds := simage.Bounds()
  palettedImage := image.NewPaletted(bounds, nil)
  quantizer := gogif.MedianCutQuantizer{NumColor: 64}
  quantizer.Quantize(palettedImage, bounds, simage, image.ZP)

  // Add new frame to animated GIF
  outGif.Image = append(outGif.Image, palettedImage)
  outGif.Delay = append(outGif.Delay, 0)
}
gif.EncodeAll(w, outGif)
like image 116
Taylor Hughes Avatar answered Feb 04 '23 01:02

Taylor Hughes


Instead of generating your own palette, you can also use on of the predefined (https://golang.org/pkg/image/color/palette/)

...
palettedImage := image.NewPaletted(bounds, palette.Plan9)
draw.Draw(palettedImage, palettedImage.Rect, simage, bounds.Min, draw.Over)
...
like image 26
Mads Sejersen Avatar answered Feb 04 '23 01:02

Mads Sejersen