最近基于现在环境,无法录屏,但又想制作连续的步骤流程。因此想到图片生成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)
}
————————————————
版权声明:本文为CSDN博主「CrazyWorkers」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/CrazyWorkers/article/details/112324356