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

时间:2015-08-25 20:06:01

标签: go jpeg

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

1 个答案:

答案 0 :(得分: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)

请注意,除了从p点开始的半径为r的圆圈外,它需要一个矩形并屏蔽所有内容。完整的文章可以在http://blog.golang.org/go-imagedraw-package

找到

在你的情况下,你希望面具只是你的正常背景,src是你想要使用的当前矩形图像。