golang 多张图片生成gif

国内关于自定义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)
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值