1. 读取图片文件
import (
"fmt"
"image"
_ "image/jpeg" //如果要解析jpg,jpeg格式的图片, 必须引入这个包
_ "image/png" //如果要解析png格式的图片, 必须引入这个包
"os"
)
func main() {
imageFilePath := "F:\\goworkspace\\caixukun\\1.jpg"
f, err := os.Open(imageFilePath)
if err != nil {
panic(err)
}
img, formatName, err := image.Decode(f)
if err != nil {
panic(err)
}
fmt.Println(formatName)
fmt.Println(img.Bounds())
fmt.Println(img.ColorModel())
}
返回结果
2. 读取图片中的像素颜色
//RGBA介绍: https://baike.baidu.com/item/RGBA/3674658
func main() {
imageFilePath := "F:\\goworkspace\\caixukun\\1.jpg"
f, _ := os.Open(imageFilePath)
img, _, _ := image.Decode(f)
color := img.At(1, 494)
r, g, b, a := color.RGBA()
fmt.Println("red = ", r>>8) //红; 转换成 0 ~ 255 展示
fmt.Println("green = ", g>>8) //绿; 转换成 0 ~ 255 展示
fmt.Println("blue = ", b>>8) //蓝; 转换成 0 ~ 255 展示
fmt.Println("alpha = ", a>>8) //透明度, 转换成 0 ~ 255 展示; 0为完全透明; 255为完全不透明
}
3. 保存图片
func main() {
newImg := image.NewRGBA(image.Rect(0, 0, 200, 200)) //创建一个200*200的全透明空白图片
newFile, _ := os.Create("F:\\goworkspace\\caixukun\\2.png")
defer newFile.Close()
buffer := bufio.NewWriter(newFile)
png.Encode(buffer, newImg)
buffer.Flush()
}
图片的rgba图片和ycbcr图片操作不一样, 有缘注意一下
4. 裁剪图片
5. 绘制图片
todo