Golang如何从矩形jpeg中裁剪圆形图像.

Kod*_*rty 3 jpeg go

在Golang中,如何从矩形jpeg中裁剪圆形图像.矩形的大小可以变化.如果你有一个图像.图像会从图像的中心裁剪出一个圆圈,圆圈占据尽可能多的空间吗?我想保留圆圈并移除其余部分.

eva*_*nal 5

这个使用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)
Run Code Online (Sandbox Code Playgroud)

请注意,它需要一个矩形和口罩的一切,但在点开始圆p半径r.完整的文章可以在http://blog.golang.org/go-imagedraw-package找到

在你的情况下,你希望掩码只是你的正常背景,src是你想要使用的当前矩形图像的一部分.