1. 读取图片文件

  1. import (
  2. "fmt"
  3. "image"
  4. _ "image/jpeg" //如果要解析jpg,jpeg格式的图片, 必须引入这个包
  5. _ "image/png" //如果要解析png格式的图片, 必须引入这个包
  6. "os"
  7. )
  8. func main() {
  9. imageFilePath := "F:\\goworkspace\\caixukun\\1.jpg"
  10. f, err := os.Open(imageFilePath)
  11. if err != nil {
  12. panic(err)
  13. }
  14. img, formatName, err := image.Decode(f)
  15. if err != nil {
  16. panic(err)
  17. }
  18. fmt.Println(formatName)
  19. fmt.Println(img.Bounds())
  20. fmt.Println(img.ColorModel())
  21. }

返回结果
image.png

2. 读取图片中的像素颜色

  1. //RGBA介绍: https://baike.baidu.com/item/RGBA/3674658
  2. func main() {
  3. imageFilePath := "F:\\goworkspace\\caixukun\\1.jpg"
  4. f, _ := os.Open(imageFilePath)
  5. img, _, _ := image.Decode(f)
  6. color := img.At(1, 494)
  7. r, g, b, a := color.RGBA()
  8. fmt.Println("red = ", r>>8) //红; 转换成 0 ~ 255 展示
  9. fmt.Println("green = ", g>>8) //绿; 转换成 0 ~ 255 展示
  10. fmt.Println("blue = ", b>>8) //蓝; 转换成 0 ~ 255 展示
  11. fmt.Println("alpha = ", a>>8) //透明度, 转换成 0 ~ 255 展示; 0为完全透明; 255为完全不透明
  12. }

image.png

3. 保存图片

  1. func main() {
  2. newImg := image.NewRGBA(image.Rect(0, 0, 200, 200)) //创建一个200*200的全透明空白图片
  3. newFile, _ := os.Create("F:\\goworkspace\\caixukun\\2.png")
  4. defer newFile.Close()
  5. buffer := bufio.NewWriter(newFile)
  6. png.Encode(buffer, newImg)
  7. buffer.Flush()
  8. }

图片的rgba图片和ycbcr图片操作不一样, 有缘注意一下


4. 裁剪图片


5. 绘制图片

todo