ZBLOG

golang image对象旋转180

要在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助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=10800

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?