Go语言中对图像文件的处理可以说是非常方便的,标准库中的image包及其子包中提供了对主流图片格式的识别处理以及对图片的加工、转换的功能。本节将对几个基本的图片文件处理功能做简单的介绍,本书后面还有专门的章节详细探讨图像处理。
打开不同格式的图像文件读取数据
利用image包及其jpeg、png、gif等子包,可以方便地实现从主流的图像文件中读取图片数据和相关信息。
package main
import (
"image"
"image/gif"
"image/jpeg"
"image/png"
"os"
"path/filepath"
"strings"
t "tools"
)
func main() {
fileNameT := `c:\test\indicator1.png`
fileT, errT := os.Open(fileNameT)
if errT != nil {
t.Printfln("打开图片文件时发生错误:%v", errT.Error())
return
}
defer fileT.Close()
fileExtT :=strings.ToLower(filepath.Ext(fileNameT))
var imgT image.Image
switch fileExtT {
case ".jpg":
imgT, errT = jpeg.Decode(fileT)
case ".png":
imgT, errT = png.Decode(fileT)
case ".gif":
imgT, errT = gif.Decode(fileT)
default:
imgT, errT = jpeg.Decode(fileT) //默认按jpg格式处理
}
if errT != nil {
t.Printfln("图片解码时发生错误:%v", errT.Error())
return
}
bounds := imgT.Bounds()
t.Printfln("图片的宽度为:%v像素,高度为:%v像素", bounds.Dx(),
bounds.Dy())
}
代码 9‑41 打开并读取图像文件数据
代码9‑41中,演示了如何打开一个图片文件并将其中图像数据和附加信息读取出来。
-> 本例虽然送入的图片文件是png格式的图片文件(测试时拷贝任意一个png格式的图片文件到c:\test目录即可),但实际上还可以识别jpg格式和gif格式的图片文件,这三种图片格式都是目前最主流的图片格式;
-> 本代码中是根据图片文件的扩展名来判断图片的具体格式的,这在通常情况下也够用了;
-> 获取文件扩展名时使用了filepath包的Ext函数,该函数用于从一个完整的文件名中获取扩展名部分(包括扩展名前面的小数点符号“.”);
-> 获取图片文件扩展名后,将其用strings.ToLower函数转换成全小写字母,然后用一个switch语句进行逐个判断,默认是jpg格式;另外,jpg格式还有一个常用的扩展名是jpeg,所以该case项中把这两个扩展名都写上了;
-> 判断出文件类型后,据此调用不同子包中的Decode函数来将其解码为统一格式的图片数据,即image.Image类型的数据;
-> 最后,调用Image.Bounds函数获取图片的宽度与高度信息并输出供参考。
整段代码非常简单,可以看出Go语言处理图像文件的便捷性,代码9‑41的运行结果如下(具体信息根据图片文件的不同可能会有所不同):
图片的宽度为:128像素,高度为:128像素
转换图像文件格式并保存
转换图片格式并保存为另一种格式的文件也是非常容易的。
package main
import (
"image"
"image/gif"
"image/jpeg"
"image/png"
"os"
"path/filepath"
"strings"
t "tools"
)
func main() {
fileNameT := `c:\test\indicator1.png`
fileT, errT := os.Open(fileNameT)
if errT != nil {
t.Printfln("打开图片文件时发生错误:%v", errT.Error())
return
}
defer fileT.Close()
fileExtT :=strings.ToLower(filepath.Ext(fileNameT))
var imgT image.Image
switch fileExtT {
case ".jpg", ".jpeg":
imgT, errT = jpeg.Decode(fileT)
case ".png":
imgT, errT = png.Decode(fileT)
case ".gif":
imgT, errT = gif.Decode(fileT)
default:
imgT, errT = jpeg.Decode(fileT) //默认按jpg格式处理
}
if errT != nil {
t.Printfln("图片解码时发生错误:%v", errT.Error())
return
}
bounds := imgT.Bounds()
t.Printfln("图片的宽度为:%v像素,高度为:%v像素", bounds.Dx(),
bounds.Dy())
newFileT, errT :=os.Create(`c:\test\indicator1.jpg`)
if errT != nil {
t.Printfln("创建新文件时发生错误:%v", errT.Error())
return
}
defer newFileT.Close()
errT = jpeg.Encode(newFileT, imgT, nil)
if errT != nil {
t.Printfln("编码为jpg格式时发生错误:%v", errT.Error())
return
}
t.Printfln("图片已转换为jpg格式,并转存为c:\\test\\indicator1.jpg")
}
代码 9‑42 转换图像格式并另存为新格式的图片
代码9‑42前半段与代码9‑41完全相同,只是在读取png格式的图片数据后,将其转换为jpg格式并保存为indicator1.jpg文件。其中最核心的只有一条语句:即调用image/jpeg包中的Encode函数来将image.Image类型的图片数据编码为jpg格式并保存进指定的文件中。
代码9‑42运行后,在“c:\test”目录下将新生成一个indicator1.jpg文件,用一般的图片文件查看软件即可确认其是否转换正常。代码9‑42的运行结果:
图片的宽度为:128像素,高度为:128像素
图片已转换为jpg格式,并转存为c:\test\indicator1.jpg