Go语言旅途之生成png图片

4,965 阅读2分钟

生成一张png图片

创建RGBA图像

background := image.NewRGBA(image.Rect(0,0,500,500))
go文档接口说明,image.Rect指定图像的左下角和右上角
func Rect(x0, y0, x1, y1 int) Rectangle
type Rectangle struct{
      Min,Max Point
}

image.NewRGBA生成一张图像,图像的结构为RGBA定义如下:

// RGBA is an in-memory image whose At method returns color.RGBA values.
type RGBA struct {
	// Pix holds the image's pixels, in R, G, B, A order. The pixel at
	// (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*4].
	Pix []uint8
	// Stride is the Pix stride (in bytes) between vertically adjacent pixels.
	Stride int
	// Rect is the image's bounds.
	Rect Rectangle
}

func NewRGBA(r Rectangle) *RGBA {
	w, h := r.Dx(), r.Dy()
	buf := make([]uint8, 4*w*h)
	return &RGBA{buf, 4 * w, r}
}

以上,我成功地在内存中创建了一张图像,但这张图像不是png格式,也没有写进硬盘。

创建文件

outFile,err := os.Create("p1.png")
接口说明:
// Create creates or truncates the named file. If the file already exists,
// it is truncated. If the file does not exist, it is created with mode 0666
// (before umask). If successful, methods on the returned File can
// be used for I/O; the associated file descriptor has mode O_RDWR.
// If there is an error, it will be of type *PathError.
func Create(name string) (*File, error) {
	return OpenFile(name, O_RDWR|O_CREATE|O_TRUNC, 0666)
}

关闭文件

defer是go的语言特性,在离开作用域时会执行defer声明的语句

defer outFile.Close()

写文件

将数据直接写进硬盘的开销较大,通常情况下是先写内存缓存,在适当时候再写进硬盘。 bufio包实现了有缓冲的I/O。它包装一个io.Reader或io.Writer接口对象,创建另一个也实现了该接口,且同时还提供了缓冲和一些文本I/O的帮助函数的对象。

接口说明:
buff := bufio.NewWriter(outFile)
func NewWriter(w io.Writer)) *Writer
// Writer implements buffering for an io.Writer object.
// If an error occurs writing to a Writer, no more data will be
// accepted and all subsequent writes, and Flush, will return the error.
// After all data has been written, the client should call the
// Flush method to guarantee all data has been forwarded to
// the underlying io.Writer.
type Writer struct {
	err error
	buf []byte
	n   int
	wr  io.Writer
}

将RGBA格式转换为PNG格式

png.Encode(buff,background)

将文件刷到硬盘png.Encode(buff,background)

buff.Flush()

至此完成了一个简单的程序

以下为代码链接 github.com/wuzhuorui/W…