golang 多张图片生成gif
程序员文章站
2022-03-24 18:43:58
...
国内关于自定义golang palette的资料比较少,特地记录分享出来
下面是多张图片生成gif的示例代码
package main
import (
"fmt"
"image"
"image/color"
"image/color/palette"
"image/draw"
"image/gif"
"image/png"
"os"
)
func isInPalette(p color.Palette, c color.Color) int {
ret := -1
for i, v := range p {
if v == c {
return i
}
}
return ret
}
func getPalette(m image.Image) color.Palette {
p := color.Palette{color.RGBA{0x00,0x00,0x00,0x00}}
p9 := color.Palette(palette.Plan9)
b := m.Bounds()
black := false
for y := b.Min.Y; y < b.Max.Y; y++ {
for x := b.Min.X; x < b.Max.X; x++ {
c := m.At(x, y)
cc := p9.Convert(c)
if cc == p9[0] {
black = true
}
if isInPalette(p, cc) == -1 {
p = append(p, cc)
}
}
}
if len(p) < 256 && black == true {
p[0] = color.RGBA{0x00,0x00,0x00,0x00} // transparent
p = append(p, p9[0])
}
return p
}
func main() {
var disposals []byte
var images []*image.Paletted
var delays []int
for i := 1; i < 50; i++ {
var src string
if i < 10 {
src = fmt.Sprintf("zi_00%d.png", i)
} else {
src = fmt.Sprintf("zi_0%d.png", i)
}
file, err := os.Open(src)
if err != nil {
fmt.Println(err)
}
defer func() { _ = file.Close() }()
g, err := png.Decode(file)
if err != nil {
fmt.Println(err)
}
cp := getPalette(g)
//cp:=append(palette.WebSafe,color.Transparent)
disposals = append(disposals, gif.DisposalBackground)//透明图片需要设置
p := image.NewPaletted(image.Rect(0, 0, 640,996),cp)
draw.Draw(p, p.Bounds(), g, image.ZP, draw.Src)
images = append(images, p)
delays = append(delays,4)
}
g := &gif.GIF{
Image: images,
Delay: delays,
LoopCount: -1,
Disposal: disposals,
}
f, err := os.Create("test1.gif")
if err != nil {
fmt.Println(err)
}
defer func() { _ = f.Close() }()
gif.EncodeAll(f, g)
}
上一篇: 微信卡娃微卡怎么制作?
下一篇: PHP文件操作功能函数大全