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

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

简单旋转分为顺时针旋转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

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