素材
132.jpg
a.jpg
代码
package main
import (
"embed"
"fmt"
"github.com/golang/freetype"
"github.com/nfnt/resize"
"image"
"image/color"
"image/draw"
"image/jpeg"
"image/png"
"io/ioutil"
"math"
"os"
"time"
)
//go:embed a.jpg 132.jpg
var fs embed.FS
func main() {
now := time.Now()
err := poster()
since := time.Since(now)
fmt.Println(since, err)
}
func poster() error {
back, err := fs.Open("a.jpg")
if err != nil {
return err
}
code, err := fs.Open("132.jpg")
if err != nil {
return err
}
badec, err := jpeg.Decode(back)
if err != nil {
return err
}
codec, err := jpeg.Decode(code)
if err != nil {
return err
}
ri := resize.Resize(55, 0, codec, resize.Lanczos3)
ri = NewCircle(ri, 26)
rgba := image.NewRGBA(badec.Bounds())
draw.Draw(rgba, rgba.Bounds(), badec, image.Point{
X: 0,
Y: 0,
}, draw.Src)
draw.Draw(rgba, rgba.Bounds(), ri, image.Point{
X: -389,
Y: -10,
}, draw.Over)
err = drawText(rgba, "水ni23好ཀᮨ້໌ꦿꦸ钟᭄", 470, 40)
if err != nil {
return err
}
create, err := os.Create("new.png")
if err != nil {
return err
}
err = png.Encode(create, rgba)
return err
}
func drawText(dst draw.Image, s string, x, y int) error {
file, err := ioutil.ReadFile("C:/Windows/Fonts/MSYHL.TTC")
if err != nil {
return err
}
font, err := freetype.ParseFont(file)
if err != nil {
return err
}
con := freetype.NewContext()
con.SetFont(font)
con.SetFontSize(18)
con.SetDst(dst)
con.SetSrc(image.White)
con.SetClip(dst.Bounds())
_, err = con.DrawString(s, freetype.Pt(x, y))
return err
}
type Circle struct {
src image.Image
r float64
center image.Point
}
func NewCircle(src image.Image, r float64) *Circle {
c := &Circle{src: src, r: r}
min := src.Bounds().Min
max := src.Bounds().Max
x := min.X + (max.X-min.X)/2
y := min.Y + (max.Y-min.Y)/2
c.center = image.Point{
X: x,
Y: y,
}
return c
}
func (c *Circle) ColorModel() color.Model {
return c.src.ColorModel()
}
func (c *Circle) Bounds() image.Rectangle {
return c.src.Bounds()
}
func (c *Circle) At(x, y int) color.Color {
i := x - c.center.X
j := y - c.center.Y
p1 := math.Pow(float64(i), 2)
p2 := math.Pow(float64(j), 2)
sqrt := math.Sqrt(p1 + p2)
if sqrt <= c.r {
return c.src.At(x, y)
}
return color.Transparent
}
效果