Golang how do you crop a circular image out of a rectangular jpeg.

huangapple go评论85阅读模式
英文:

Golang how do you crop a circular image out of a rectangular jpeg.

问题

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

英文:

In Golang how do you crop a circular image out of a rectangular jpeg. The rectangle can vary in size. If you have an image.Image would you crop out a circle from the center of the image where the circle takes up as much space as possible? I want to keep the circle and remove the rest.

答案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)

请注意,它接受一个矩形,并使用以点p为起点、半径为r的圆形遮罩除了圆形之外的所有内容。完整的文章可以在这里找到:http://blog.golang.org/go-imagedraw-package

在你的情况下,你希望遮罩只是你的普通背景,而源图像是你想要使用部分的矩形图像。

英文:

This example using the drawing package from the golang blog should do roughly what you want;

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 &lt; rr*rr {
        return color.Alpha{255}
    }
    return color.Alpha{0}
}

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

Note that it takes a rectangle and masks everything but the circle beginning at point p with radius r. The full article can be found here http://blog.golang.org/go-imagedraw-package

In your case you would like the mask to just be your normal background and the src to be the currently rectangular image you'd like to use part of.

huangapple
  • 本文由 发表于 2015年8月26日 04:06:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/32213093.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定