如何在矩形JPEG图像中裁剪出圆形图像(Golang)

5

在Golang中,如何从矩形JPEG图像中剪裁出圆形图像。矩形的大小可能会有所不同。如果您有一个图像.Image,您要从图像中心剪切出一个圆圈,其中圆圈占据尽可能多的空间吗?我想保留圆圈并删除其余部分。

1个回答

7

这个例子使用了Golang博客中的绘图包,应该大致能够满足您的需求;

type circle struct {
    p image.Point
    r int
}

func (c *circle) ColorModel() color.Model {
    return color.AlphaModel
}

func (c *circle) Bounds() image.Rectangle {
    return image.Rect(c.p.X-c.r, c.p.Y-c.r, c.p.X+c.r, c.p.Y+c.r)
}

func (c *circle) At(x, y int) color.Color {
    xx, yy, rr := float64(x-c.p.X)+0.5, float64(y-c.p.Y)+0.5, float64(c.r)
    if xx*xx+yy*yy < rr*rr {
        return color.Alpha{255}
    }
    return color.Alpha{0}
}

    draw.DrawMask(dst, dst.Bounds(), src, image.ZP, &circle{p, r}, image.ZP, draw.Over)

请注意,此函数接受一个矩形,并使用半径为r的圆从点p开始掩盖除圆外的所有内容。完整的文章可以在这里找到:http://blog.golang.org/go-imagedraw-package 在您的情况下,您希望掩码只是普通背景,源应该是您想要使用部分的当前矩形图像。

根据您的想法:https://goplay.space/#_RTH0rWA7Ae - Metal3d

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接