Created
April 26, 2024 13:32
-
-
Save chumaumenze/1c7c4480daaf9fab3f80be65689dffea to your computer and use it in GitHub Desktop.
Make rounded images in Golang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Make rounded images in Golang |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"image" | |
"image/color" | |
"image/draw" | |
) | |
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{A: 255} | |
} | |
return color.Alpha{} | |
} | |
// RoundImage creates a new rounded image from source | |
func RoundImage(source image.Image) image.Image { | |
b := source.Bounds() | |
var radius int | |
if b.Max.X <= b.Max.Y { | |
radius = b.Max.X / 2 | |
} else { | |
radius = b.Max.Y / 2 | |
} | |
c := &circle{ | |
p: image.Point{X: b.Dx() / 2, Y: b.Dy() / 2}, | |
r: radius, | |
} | |
result := image.NewRGBA(c.Bounds()) | |
var ZP image.Point | |
draw.DrawMask(result, source.Bounds(), source, ZP, c, ZP, draw.Over) | |
return result | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"image" | |
"image/png" | |
"log" | |
"os" | |
) | |
func loadPng(name string) (image.Image, string, error) { | |
img, err := os.Open(name) | |
if err != nil { | |
return nil, "", err | |
} | |
defer img.Close() | |
return image.Decode(img) | |
} | |
func main() { | |
source, _, err := loadPng("path/to/my/image.png") | |
if err != nil { | |
log.Fatal(err.Error()) | |
} | |
rounded := RoundImage(source) | |
outputFile, err := os.Create("rounded.png") | |
if err != nil { | |
log.Fatal(err.Error()) | |
} | |
defer outputFile.Close() | |
png.Encode(outputFile, rounded) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment