一、环境准备
在开始之前,确保你的系统中已经安装了Go语言环境。你可以从下载并安装Go。
二、图片读取
package main
import (
"fmt"
"image"
"image/jpeg"
"os"
)
func main() {
// 打开文件
file, err := os.Open("example.jpg")
if err != nil {
fmt.Println("Error opening file:", err)
return
}
defer file.Close()
// 解码JPEG图片
img, _, err := image.Decode(file)
if err != nil {
fmt.Println("Error decoding image:", err)
return
}
// 输出图片尺寸
fmt.Printf("Image size: %dx%d\n", img.Bounds().Dx(), img.Bounds().Dy())
}
三、图片输出
package main
import (
"fmt"
"image"
"image/jpeg"
"os"
)
func main() {
// 假设img是已经处理好的图片
img := image.NewRGBA(image.Rect(0, 0, 100, 100))
// 创建文件
file, err := os.Create("output.jpg")
if err != nil {
fmt.Println("Error creating file:", err)
return
}
defer file.Close()
// 编码JPEG图片
err = jpeg.Encode(file, img, &jpeg.Options{Quality: 90})
if err != nil {
fmt.Println("Error encoding image:", err)
return
}
}
四、图片优化
1. 压缩图片
2. 调整图片尺寸
package main
import (
"fmt"
"image"
"image/jpeg"
"os"
)
func main() {
original := image.NewRGBA(image.Rect(0, 0, 100, 100))
processed := image.NewRGBA(image.Rect(0, 0, 50, 50))
// 调整图片尺寸
bounds := processed.Bounds()
for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
for x := bounds.Min.X; x < bounds.Max.X; x++ {
originalPos := image.Point{x*2, y*2}
processed.Set(x, y, original.At(originalPos.X, originalPos.Y))
}
}
// 输出处理后的图片
file, err := os.Create("output_small.jpg")
if err != nil {
fmt.Println("Error creating file:", err)
return
}
defer file.Close()
err = jpeg.Encode(file, processed, &jpeg.Options{Quality: 90})
if err != nil {
fmt.Println("Error encoding image:", err)
return
}
}