分享
  1. 首页
  2. 文章

Golang 图片处理(旋转/居中)

韬大帅 · · 4751 次点击 · · 开始浏览
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

简单旋转分为顺时针旋转90度,顺时针旋转180度,顺时针旋转270度。说到底其实就是矩阵旋转,将各个像素点的色值重新赋值

// 旋转90度
func rotate90(m image.Image) image.Image {
 rotate90 := image.NewRGBA(image.Rect(0, 0, m.Bounds().Dy(), m.Bounds().Dx()))
 // 矩阵旋转
 for x := m.Bounds().Min.Y; x < m.Bounds().Max.Y; x++ {
 for y := m.Bounds().Max.X - 1; y >= m.Bounds().Min.X; y-- {
 // 设置像素点
 rotate90.Set(m.Bounds().Max.Y-x, y, m.At(y, x))
 }
 }
 return rotate90
}
// 旋转180度
func rotate180(m image.Image) image.Image {
 rotate180 := image.NewRGBA(image.Rect(0, 0, m.Bounds().Dx(), m.Bounds().Dy()))
 // 矩阵旋转
 for x := m.Bounds().Min.X; x < m.Bounds().Max.X; x++ {
 for y := m.Bounds().Min.Y; y < m.Bounds().Max.Y; y++ {
 // 设置像素点
 rotate180.Set(m.Bounds().Max.X-x, m.Bounds().Max.Y-y, m.At(x, y))
 }
 }
 return rotate180
}
// 旋转270度
func rotate270(m image.Image) image.Image {
 rotate270 := image.NewRGBA(image.Rect(0, 0, m.Bounds().Dy(), m.Bounds().Dx()))
 // 矩阵旋转
 for x := m.Bounds().Min.Y; x < m.Bounds().Max.Y; x++ {
 for y := m.Bounds().Max.X - 1; y >= m.Bounds().Min.X; y-- {
 // 设置像素点
 rotate270.Set(x, m.Bounds().Max.X-y, m.At(y, x))
 }
 }
 return rotate270
}

还有个需求就是将长方形图片修改为正方形图片,原图片居中显示(这里是长>=宽)

// 将图片居中处理
func (i infoService) centerImage(m image.Image) image.Image {
 // 现在图片是长>宽,将图片居中设置
 max := m.Bounds().Dx()
 // 居中后距离最底部的高度为(x-y)/2
 temp := (max - m.Bounds().Dy()) / 2
 centerImage := image.NewRGBA(image.Rect(0, 0, max, max))
 for x := m.Bounds().Min.X; x < m.Bounds().Max.X; x++ {
 for y := m.Bounds().Min.Y; y < m.Bounds().Max.Y; y++ {
 centerImage.Set(x, temp+y, m.At(x, y))
 }
 }
 return centerImage
}

有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:韬大帅

查看原文:Golang 图片处理(旋转/居中)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

关注微信
4751 次点击
添加一条新回复 (您需要 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传

用户登录

没有账号?注册
(追記) (追記ここまで)

今日阅读排行

    加载中
(追記) (追記ここまで)

一周阅读排行

    加载中

关注我

  • 扫码关注领全套学习资料 关注微信公众号
  • 加入 QQ 群:
    • 192706294(已满)
    • 731990104(已满)
    • 798786647(已满)
    • 729884609(已满)
    • 977810755(已满)
    • 815126783(已满)
    • 812540095(已满)
    • 1006366459(已满)
    • 692541889

  • 关注微信公众号
  • 加入微信群:liuxiaoyan-s,备注入群
  • 也欢迎加入知识星球 Go粉丝们(免费)

给该专栏投稿 写篇新文章

每篇文章有总共有 5 次投稿机会

收入到我管理的专栏 新建专栏