加载和保存图像
在存储器中,图像可以被视为像素(颜色)的矩阵。但是,当图像存储在永久存储器中时,它可以按原样存储(RAW 格式),位图或其他具有特定压缩算法的图像格式,以节省存储空间,例如 PNG,JPEG,GIF 等。加载图像时对于特定格式,必须使用相应的算法将图像解码为 image.Image。一个 image.Decode函数声明为
func Decode(r io.Reader) (Image, string, error)
提供此特定用法。为了能够处理各种图像格式,在调用 image.Decode 函数之前,解码器必须通过定义为 image.RegisterFormat 的函数进行注册。
func RegisterFormat(name, magic string,
decode func(io.Reader) (Image, error), decodeConfig func(io.Reader) (Config, error))
目前,图像包支持三种文件格式: JPEG , GIF 和 PNG 。要注册解码器,请添加以下内容
import _ "image/jpeg" //register JPEG decoder
到应用程序的 main 包。在代码中的某处(main 包中不需要),要加载 JPEG 图像,请使用以下代码段:
f, err := os.Open("inputimage.jpg")
if err != nil {
// Handle error
}
defer f.Close()
img, fmtName, err := image.Decode(f)
if err != nil {
// Handle error
}
// `fmtName` contains the name used during format registration
// Work with `img` ...
保存到 PNG
要将图像保存为特定格式,必须明确导入相应的编码器,即
import "image/png" //needed to use `png` encoder
然后可以使用以下代码段保存图像:
f, err := os.Create("outimage.png")
if err != nil {
// Handle error
}
defer f.Close()
// Encode to `PNG` with `DefaultCompression` level
// then save to file
err = png.Encode(f, img)
if err != nil {
// Handle error
}
如果要指定 DefaultCompression 级别以外的压缩级别,请创建编码器,例如
enc := png.Encoder{
CompressionLevel: png.BestSpeed,
}
err := enc.Encode(f, img)
保存为 JPEG
要保存为 jpeg 格式,请使用以下命令:
import "image/jpeg"
// Somewhere in the same package
f, err := os.Create("outimage.jpg")
if err != nil {
// Handle error
}
defer f.Close()
// Specify the quality, between 0-100
// Higher is better
opt := jpeg.Options{
Quality: 90,
}
err = jpeg.Encode(f, img, &opt)
if err != nil {
// Handle error
}
保存到 GIF
要将图像保存为 GIF 文件,请使用以下代码段。
import "image/gif"
// Samewhere in the same package
f, err := os.Create("outimage.gif")
if err != nil {
// Handle error
}
defer f.Close()
opt := gif.Options {
NumColors: 256,
// Add more parameters as needed
}
err = gif.Encode(f, img, &opt)
if err != nil {
// Handle error
}