在开发中,有时会遇到对图片的处理需求,在 Python中, PIL/Pillow 库非常强大和易用。
而 Golang 语言中,处理图片的标准库 image也可以实现一些基本操作。
image 库支持常见的 PNG、JPEG、GIF 等格式的图片处理, 可以对图片进行读取、裁剪、绘制、生成等操作。

读取

图片的读取,和文件的读取类似,只需要使用 os.Open()函数,获取一个输入流,然后将数据流进行解码操作。
需要注意的是,在解码阶段,要将不同类型的图片的解码器先进行注册,这样才不会报unknown format 的错误。

  1. package main
  2. import (
  3. "fmt"
  4. "image"
  5. _ "image/png"
  6. "os"
  7. )
  8. func main() {
  9. f, err := os.Open("./gopher.png")
  10. if err != nil {
  11. panic(err)
  12. }
  13. img, formatName, err := image.Decode(f)
  14. if err != nil {
  15. panic(err)
  16. }
  17. fmt.Println(formatName)
  18. fmt.Println(img.Bounds())
  19. fmt.Println(img.ColorModel())
  20. }

Decode方法返回的第一个值是一个 image.Image类型接口。不同的颜色模型的图片返回不同类型的值。该接口有三个方法:

image 库中很多结构都实现了该接口,对于一些标准库中没有实现的功能,我们也可以自己实现该接口去满足。

新建

如果是需要新建一个图片,可以使用image.NewRGBA()方法。

  1. img := image.NewRGBA(image.Rect(0, 0, 300, 300))

这里的 NewRGBA方法返回的是一个实现了 image.Image接口的 image.RGBA类型数据。这里是一个300*300的透明背景的图片。

保存图片

  1. img := image.NewRGBA(image.Rect(0, 0, 300, 300))
  2. outFile, err := os.Create("gopher2.png")
  3. defer outFile.Close()
  4. if err != nil {
  5. panic(err)
  6. }
  7. b := bufio.NewWriter(outFile)
  8. err = png.Encode(b, img)
  9. if err != nil {
  10. panic(err)
  11. }
  12. err = b.Flush()
  13. if err != nil {
  14. panic(err)
  15. }

裁剪图片
图片的裁剪主要使用SubImage()方法,如下:

  1. img := image.NewRGBA(image.Rect(0, 0, 300, 300))
  2. subImage := img.SubImage(image.Rect(0, 0, 20, 20))

该方法将从创建的300 300的图片裁剪出20 20 像素的子图片。

绘制图片
绘制图片主要使用到draw.Drawdraw.DrawMask方法。

  1. func Draw(dst Image, r image.Rectangle, src image.Image, sp image.Point, op Op)
  2. func DrawMask(dst Image, r image.Rectangle, src image.Image, sp image.Point, mask image.Image, mp image.Point, op Op)

Draw

Draw方法各个参数含义如下:

  • dst 绘图的背景图
  • r 背景图的绘图区域
  • src 要绘制的图
  • sp src 对应的绘图开始点
  • op 组合方式

以下代码是将一个 Gopher 的图案绘制到了一张黑色背景空白图的左上角。

  1. f, err := os.Open("./gopher.png")
  2. if err != nil {
  3. panic(err)
  4. }
  5. gopherImg, _, err := image.Decode(f) // 打开图片
  6. img := image.NewRGBA(image.Rect(0, 0, 300, 300))
  7. for x := 0; x < img.Bounds().Dx(); x++ { // 将背景图涂黑
  8. for y := 0; y < img.Bounds().Dy(); y++ {
  9. img.Set(x, y, color.Black)
  10. }
  11. }
  12. draw.Draw(img, img.Bounds(), gopherImg, image.Pt(0, 0), draw.Over) // 将gopherImg绘制到背景图上

image.png

DrawMask

DrawMask方法多了一个遮罩蒙层参数mask,以及蒙层的起始位置参数 mp。

Draw方法是 DrawMask的一种特殊形式,当 DrawMask 的 mask 参数为nil时,即为Draw方法。

DrawMask将背景图上的绘图区域起始点、要绘制图的起始点、遮罩蒙层的起始点进行对齐,然后对背景图上的绘图矩阵区域执行 Porter-Duff合并操作。

下面是给图片加一个圆形遮罩的示例:

  1. func drawCirclePic() {
  2. f, err := os.Open("./gopher.png")
  3. if err != nil {
  4. panic(err)
  5. }
  6. gopherImg, _, err := image.Decode(f)
  7. d := gopherImg.Bounds().Dx()
  8. //将一个cicle作为蒙层遮罩,圆心为图案中点,半径为边长的一半
  9. c := circle{p: image.Point{X: d / 2, Y: d / 2}, r: d / 2}
  10. circleImg := image.NewRGBA(image.Rect(0, 0, d, d))
  11. draw.DrawMask(circleImg, circleImg.Bounds(), gopherImg, image.Point{}, &c, image.Point{}, draw.Over)
  12. SavePng(circleImg)
  13. }
  14. type circle struct { // 这里需要自己实现一个圆形遮罩,实现接口里的三个方法
  15. p image.Point // 圆心位置
  16. r int
  17. }
  18. func (c *circle) ColorModel() color.Model {
  19. return color.AlphaModel
  20. }
  21. func (c *circle) Bounds() image.Rectangle {
  22. return image.Rect(c.p.X-c.r, c.p.Y-c.r, c.p.X+c.r, c.p.Y+c.r)
  23. }
  24. // 对每个像素点进行色值设置,在半径以内的图案设成完全不透明
  25. func (c *circle) At(x, y int) color.Color {
  26. xx, yy, rr := float64(x-c.p.X)+0.5, float64(y-c.p.Y)+0.5, float64(c.r)
  27. if xx*xx+yy*yy < rr*rr {
  28. return color.Alpha{A: 255}
  29. }
  30. return color.Alpha{}
  31. }

image.png
给图片加一个圆角遮罩的示例:

  1. func drawRadiusPic() {
  2. f, err := os.Open("./gopher.png")
  3. if err != nil {
  4. panic(err)
  5. }
  6. gopherImg, _, err := image.Decode(f)
  7. w := gopherImg.Bounds().Dx()
  8. h := gopherImg.Bounds().Dy()
  9. c := radius{p: image.Point{X: w, Y: h}, r: int(40)}
  10. radiusImg := image.NewRGBA(image.Rect(0, 0, w, h))
  11. draw.DrawMask(radiusImg, radiusImg.Bounds(), gopherImg, image.Point{}, &c, image.Point{}, draw.Over)
  12. SavePng(radiusImg)
  13. }
  14. type radius struct {
  15. p image.Point // 矩形右下角位置
  16. r int
  17. }
  18. func (c *radius) ColorModel() color.Model {
  19. return color.AlphaModel
  20. }
  21. func (c *radius) Bounds() image.Rectangle {
  22. return image.Rect(0, 0, c.p.X, c.p.Y)
  23. }
  24. // 对每个像素点进行色值设置,分别处理矩形的四个角,在四个角的内切圆的外侧,色值设置为全透明,其他区域不透明
  25. func (c *radius) At(x, y int) color.Color {
  26. var xx, yy, rr float64
  27. var inArea bool
  28. // left up
  29. if x <= c.r && y <= c.r {
  30. xx, yy, rr = float64(c.r-x)+0.5, float64(y-c.r)+0.5, float64(c.r)
  31. inArea = true
  32. }
  33. // right up
  34. if x >= (c.p.X-c.r) && y <= c.r {
  35. xx, yy, rr = float64(x-(c.p.X-c.r))+0.5, float64(y-c.r)+0.5, float64(c.r)
  36. inArea = true
  37. }
  38. // left bottom
  39. if x <= c.r && y >= (c.p.Y-c.r) {
  40. xx, yy, rr = float64(c.r-x)+0.5, float64(y-(c.p.Y-c.r))+0.5, float64(c.r)
  41. inArea = true
  42. }
  43. // right bottom
  44. if x >= (c.p.X-c.r) && y >= (c.p.Y-c.r) {
  45. xx, yy, rr = float64(x-(c.p.X-c.r))+0.5, float64(y-(c.p.Y-c.r))+0.5, float64(c.r)
  46. inArea = true
  47. }
  48. if inArea && xx*xx+yy*yy >= rr*rr {
  49. return color.Alpha{}
  50. }
  51. return color.Alpha{A: 255}
  52. }

image.png
在图案进行圆形、圆角绘制的过程中,因为最小单位是1px,所以可能会有锯齿边缘的问题,解决这个问题可以通过先将原图放大,遮罩后再缩小来解决。

Reference

The Go image/draw package - The Go Blog (golang.org)https://blog.golang.org/image-draw))

Porter-Duff blend 模式 - Xamarin | Microsoft Docs(https://docs.microsoft.com/zh-tw/xamarin/xamarin-forms/user-interface/graphics/skiasharp/effects/blend-modes/porter-duff
[

](https://blog.csdn.net/RA681t58CJxsgCkJ31/article/details/118425235)