Like Share Discussion Bookmark Smile

J.J. Huang   2025-07-01   Getting Started Golang 07.套件   瀏覽次數:次   DMCA.com Protection Status

Go | 影像套件的函式與介紹

💬 簡介

Go 語言的 image 套件提供了圖像處理的基礎建構功能,讓我們可以建立、操作、儲存各種圖像格式,並進一步與 image/pngimage/jpeg 等套件搭配使用。

本篇將帶你認識如何用 Go 建立一張圖片、操作像素、儲存為檔案,打開影像處理的基礎應用之門。

圖片來源:Gophers


💡 套件簡介與匯入

1
2
3
4
5
6
import (
"image"
"image/color"
"image/png"
"os"
)
套件 功能說明
image 定義圖像介面與格式
image/color 定義顏色(RGB、灰階等)
image/png 提供 PNG 圖檔編碼功能
image/jpeg 提供 JPEG 圖檔編碼功能

🖼️ 建立新圖像

建立一張空白的 100x100 畫布:

1
2
rect := image.Rect(0, 0, 100, 100)
img := image.NewRGBA(rect)
  • image.Rect(x0, y0, x1, y1):定義一個從 (x0, y0)(x1, y1) 的矩形區域。
  • image.NewRGBA():建立一個支援 RGB + Alpha 的彩色圖像。

🎨 設定像素顏色

透過 Set(x, y, color) 方法設定指定座標的顏色:

1
2
3
4
5
6
7
red := color.RGBA{255, 0, 0, 255}

for x := 0; x < 100; x++ {
for y := 0; y < 100; y++ {
img.Set(x, y, red)
}
}
  • color.RGBA{R, G, B, A}:RGBA 顏色物件,A 代表透明度(255 為不透明)

💾 儲存為 PNG 檔

1
2
3
4
5
6
7
8
9
10
file, err := os.Create("red.png")
if err != nil {
panic(err)
}
defer file.Close()

err = png.Encode(file, img)
if err != nil {
panic(err)
}

使用 image/png.Encode() 將圖像資料輸出成 PNG 圖檔。


🎯 圖像操作範例:繪製漸層方塊

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package main

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

func main() {
img := image.NewRGBA(image.Rect(0, 0, 256, 256))

for x := 0; x < 256; x++ {
for y := 0; y < 256; y++ {
col := color.RGBA{uint8(x), uint8(y), 128, 255}
img.Set(x, y, col)
}
}

f, _ := os.Create("gradient.png")
defer f.Close()
png.Encode(f, img)
}

📥 讀取圖像檔

1
2
3
4
5
6
7
8
9
10
11
12
file, err := os.Open("sample.png")
if err != nil {
panic(err)
}
defer file.Close()

img, _, err := image.Decode(file)
if err != nil {
panic(err)
}

fmt.Println("圖像尺寸:", img.Bounds())

image.Decode() 可自動判斷格式,需同時匯入對應格式的套件如 image/pngimage/jpeg 等。


🔍 常見結構與型別說明

型別 功能簡述
image.Image 圖像介面
image.RGBA 彩色圖像(Red Green Blue)
image.Gray 灰階圖像
color.Color 顏色介面
image.Rectangle 定義圖像尺寸範圍

🧰 搭配第三方工具提升功能

工具/套件 功能
golang.org/x/image/draw 圖像縮放、平移與複製操作
github.com/fogleman/gg 2D 圖形與繪圖函式包
github.com/disintegration/imaging 高階圖像處理(模糊、旋轉、調整)

⚠️ 注意事項

  • 圖像處理屬於記憶體密集操作,處理大量圖像時請注意資源釋放。
  • 輸出為 JPEG 時可使用 jpeg.Encode(file, img, &jpeg.Options{Quality: 80}) 指定品質。
  • Set() 不會觸發立即顯示,僅改變記憶體中圖像內容,需手動輸出或顯示。

🎯 總結

Go 的 image 套件提供:

  • ✅ 建立、編輯與輸出圖像的基本能力
  • ✅ 結合 image/color 可自定義色彩組合
  • ✅ 搭配其他標準函式庫完成圖檔輸出與格式解析
  • ✅ 適合基本圖像處理與影像生成的場景應用

雖然功能不如大型圖形處理框架強大,但簡單、直觀且跨平台的特性,仍使它在程式化圖像處理中扮演關鍵角色!

最後建議回顧一下 Go | 菜鳥教學 目錄,了解其章節內容。


註:以上參考了
Go