在 Go (Golang) 中处理图像:image、draw、imaging、resize

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

在 Go (Golang) 中处理图像:从基础到高级工具



Go (Golang) 提供了强大的内置工具用于处理位图图形,以及丰富的第三方库生态系统。本文将介绍标准包 image、image/color、image/draw 和 image/png,以及流行的库 imaging、resize 和 gg,用于解决常见任务:加载、调整大小、叠加、绘制和保存图像。



Go 标准图像处理包



Go 标准库提供了基本的类型和函数用于图像处理,可覆盖 80% 的日常需求。



  • image — 定义了 Image 接口和具体类型:RGBA、NRGBA、Gray、Paletted 等。
  • image/color — 描述颜色和色彩模型(Color、RGBA、NRGBA、Gray)。
  • image/draw — 提供绘制和图像叠加算法(Porter-Duff 合成)。
  • image/png、image/jpeg、image/gif — 用于读写相应格式的编解码器。


示例 1:创建并保存渐变 PNG 图像



package main

import ( "image" "image/color" "image/png" "os")

func main() { // 创建一个新的 200x200 RGBA 图像 width, height := 200, 200 img := image.NewRGBA(image.Rect(0, 0, width, height))

// 用从红到蓝的渐变填充像素 for y := 0; y < height; y++ { for x := 0; x < width; x++ { // 系数从 0 到 1 ratio := float64(x) / float64(width) r := uint8(255 * (1 - ratio)) b := uint8(255 * ratio) g := uint8(128) img.Set(x, y, color.RGBA{r, g, b, 255}) } }

// 保存到文件 f, _ := os.Create("gradient.png") defer f.Close() png.Encode(f, img)}


示例 2:加载 JPEG 并叠加文本(通过 image/draw)



package main

import ( "image" "image/color" "image/draw" "image/jpeg" "image/png" "os")

func main() { // 打开源图像 srcFile, _ := os.Open("input.jpg") defer srcFile.Close() src, _, _ := image.Decode(srcFile)

// 创建 RGBA 副本以便绘制 bounds := src.Bounds() dst := image.NewRGBA(bounds) draw.Draw(dst, bounds, src, bounds.Min, draw.Src)

// 在左上角绘制一个红色矩形 redRect := image.NewUniform(color.RGBA{255, 0, 0, 200}) rect := image.Rect(10, 10, 150, 80) draw.Draw(dst, rect, redRect, image.Point{}, draw.Over)

// 保存结果 outFile, _ := os.Create("output.png") defer outFile.Close() png.Encode(outFile, dst)}


imaging 库:高级图像处理



imaging (github.com/disintegration/imaging) 是一个流行的库,为最常见的操作提供了便捷的 API:调整大小、裁剪、旋转、应用滤镜和格式转换。



  • imaging.Open() — 从文件加载图像。
  • imaging.Resize() — 调整大小并保持比例。
  • imaging.Fit() — 适应指定矩形。
  • imaging.Fill() — 裁剪并缩放到精确尺寸。
  • imaging.Rotate() — 按指定角度旋转。
  • imaging.Blur()、imaging.Sharpen() — 滤镜。


示例 3:使用

推荐