要在Golang中将图像对象旋转180度,可以使用draw包和image包来实现。下面是一个简单的代码示例:
package main
import (
"image"
"image/draw"
"os"
)
func main() {
// 读取图片文件
file, err := os.Open("input.jpg")
if err != nil {
panic(err)
}
defer file.Close()
// 解码为图像对象
img, _, err := image.Decode(file)
if err != nil {
panic(err)
}
bounds := img.Bounds()
width, height := bounds.Max.X, bounds.Max.Y
// 创建一个新的图像对象,并进行旋转操作
newImg := image.NewRGBA(bounds)
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
oldPixel := img.At(x, y)
newX := width - x - 1
newY := height - y - 1
newImg.Set(newX, newY, oldPixel)
}
}
// 将旋转后的图像保存到文件中
outputFile, err := os.Create("output.jpg")
if err != nil {
panic(err)
}
defer outputFile.Close()
err = jpeg.Encode(outputFile, newImg, &jpeg.Options{Quality: 100})
if err != nil {
panic(err)
}
fmt.Println("Image rotated successfully!")
}
请确保已经安装了相应的依赖包(如 github.com/disintegration/imaging, golang.org/x/image/draw, golang.org/x/image/...等)并修改输入输出文件路径。此示例假设图像文件为JPEG格式,你可以根据需要调整代码以适应其他图像格式。
内容由零声教学AI助手提供,问题来源于学员提问




