image_gif灰度处理

package main

import (
	image2 "image"
	"image/color"
	"image/color/palette"
	"image/draw"
	"image/gif"
	"log"
	"os"
)

func main() {
	// 读取每一帧GIF(保存图片【图片路径列表处理】)
	var gfs *gif.GIF
	var err error
	gfs, err = readGif(`/Users/cpenny/go/src/local/ce/fang.gif`)
	dealErr(err)
	var imageList []image2.Image
	imageList, err = GenPicture(gfs)
	dealErr(err)

	// 合成GIF
	err = genGif("ceshi.gif", imageList)
	dealErr(err)

}

// 读取GIF
func readGif(gPath string) (gfs *gif.GIF, err error) {
	var gf *os.File
	gf, err = os.Open(gPath)
	dealErr(err)
	gfs, err = gif.DecodeAll(gf)
	dealErr(err)
	return gfs, err
}

// 生成图片
func GenPicture(gfs *gif.GIF) (imageList []image2.Image, err error) {
	w := gfs.Config.Width
	h := gfs.Config.Height
	if len(gfs.Image) > 0 {
		for _, gf := range gfs.Image {
			img := gf.SubImage(image2.Rect(0, 0, w, h))
			// 灰化处理
			var imgR *image2.RGBA
			imgR = hdImage(img)
			dealErr(err)
			imageList = append(imageList, imgR)
		}
	}
	return imageList, err
}

// 图片灰化处理
func hdImage(m image2.Image) *image2.RGBA {
	bounds := m.Bounds()
	dx := bounds.Dx()
	dy := bounds.Dy()
	newRgba := image2.NewRGBA(bounds)
	for i := 0; i < dx; i++ {
		for j := 0; j < dy; j++ {
			colorRgb := m.At(i, j)
			_, g, _, a := colorRgb.RGBA()
			g_uint8 := uint8(g >> 8)
			a_uint8 := uint8(a >> 8)
			newRgba.SetRGBA(i, j, color.RGBA{g_uint8, g_uint8, g_uint8, a_uint8})
		}
	}
	return newRgba
}

// 生成GIF图
func genGif(gPath string, imageList []image2.Image) (err error) {
	var gf *os.File
	gf, err = os.Create(gPath)
	dealErr(err)
	delay := 1
	if len(imageList) > 0 {
		anim := gif.GIF{}
		for _, img := range imageList {
			paletted := image2.NewPaletted(img.Bounds(), palette.Plan9)
			draw.FloydSteinberg.Draw(paletted, img.Bounds(), img, image2.ZP)

			anim.Image = append(anim.Image, paletted)
			anim.Delay = append(anim.Delay, delay*15)
		}
		err = gif.EncodeAll(gf, &anim)
		dealErr(err)
	}
	err = gf.Close()
	dealErr(err)
	return nil
}

func dealErr(err error) {
	if err != nil {
		log.Println(err)
		panic(err)
	}
}

参考链接:https://github.com/wule61/gif2ascii

你可能感兴趣的:(简易工具)