🖼 golang-图片旋转

最近在做旋转图片验证码,需要对图片进行旋转,网上没有找到类似的库,也没有扎到对应的方法,只有一些简单旋转90度,180度,达不到我的要求。自己封装一个旋转图片的方法,可以旋转任意角度
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
func TestRotating(t *testing.T)  {
// 打开源图(一张长方形的png图片)
f, _ := os.Open("C:/Users/Admin/Desktop/one.png")
// png解码
sImg, _ := png.Decode(f)
// 圆半径(需要从源图中扣出一个圆形小图)
r := sImg.Bounds().Max.Y / 4
// 构建圆图
tarImg := image.NewNRGBA(image.Rect(0 ,0 , 2 * r, 2 * r))
// 圆图的圆心
trX, trY := tarImg.Bounds().Max.X / 2, tarImg.Bounds().Max.Y / 2
// 一个像素一个像素的填充
for x := 0; x <= tarImg.Bounds().Max.X; x++ {
for y := 0; y <= tarImg.Bounds().Max.Y; y++ {
// 设置背景透明
tarImg.SetNRGBA(x, y, color.NRGBA{255, 255, 255, 0})
if (x-trX)*(x-trX) + (y-trY)*(y-trY) <= r*r { // 画圆
// 从源图中获取像素
cr, g, b, a := sImg.At(sImg.Bounds().Max.X/2-r+x, sImg.Bounds().Max.Y/2-r+y).RGBA()
// 填充到扣取的圆图
tarImg.SetNRGBA(x, y, color.NRGBA{*(*uint8)(unsafe.Pointer(&cr)), *(*uint8)(unsafe.Pointer(&g)), *(*uint8)(unsafe.Pointer(&b)), *(*uint8)(unsafe.Pointer(&a))})
}
}
}
// 构建旋转后的圆图
retImg := image.NewNRGBA(image.Rect(0 ,0 , 2 * r, 2 * r))
// 循环处理每个像素的旋转
for x := 0; x <= retImg.Bounds().Max.X; x++ {
for y := 0; y <= retImg.Bounds().Max.Y; y++ {
if (x-trX)*(x-trX) + (y-trY)*(y-trY) <= r*r { // 画圆
// 获取该点旋转后的点,这里旋转45度
tx, ty := AngleSwapPoint(float64(x), float64(y), float64(r), 45)
// 从上面扣取的圆图中获取像素
cr, g, b, a := tarImg.At(int(tx), int(ty)).RGBA()
// 填充到旋转后的圆图中
retImg.SetNRGBA(x, y, color.NRGBA{*(*uint8)(unsafe.Pointer(&cr)), *(*uint8)(unsafe.Pointer(&g)), *(*uint8)(unsafe.Pointer(&b)), *(*uint8)(unsafe.Pointer(&a))})
}
}
}
// 保存
tf, _ := os.Create("C:/Users/Admin/Desktop/tar.png")
png.Encode(tf, retImg)
tar2, _ := os.Create("C:/Users/Admin/Desktop/tar2.png")
png.Encode(tar2, tarImg)
}

// 角度转换点坐标
func AngleSwapPoint(x, y, r, angle float64) (tarX, tarY float64) {
// 坐标转换为正负x,y轴点坐标
x -= r
y = r - y
// 角度转弧度后获取sin值
sinVal := math.Sin(angle*(math.Pi/180))
cosVal := math.Cos(angle*(math.Pi/180))
// 三角函数获取旋转后点的坐标
tarX = x*cosVal + y*sinVal
tarY = -x*sinVal + y*cosVal
// 正负x,y轴点坐标转换为坐标
tarX += r
tarY = r - tarY
return
}
  • 我的运行结果:
理解AngleSwapPoin函数需要一点数学知识,有兴趣的参考下面的文章:
参考1 参考2
作者

itpika

发布于

2020-12-30 17:29:37

更新于

2021-01-28 16:44:10

许可协议

评论