golang 怎么在一张图片上画框

chenzy · · 2444 次点击
已解决 package main import ( "fmt" "image" "image/color" "image/draw" "image/jpeg" "io/ioutil" "log" "os" "github.com/golang/freetype" "github.com/llgcode/draw2d/draw2dimg" ) var m *image.RGBA func main() { f1, err := os.Open("1.jpg") if err != nil { panic(err) } f3, err := os.Create("3.jpg") if err != nil { panic(err) } defer f3.Close() //解码 m1, err := jpeg.Decode(f1) if err != nil { panic(err) } m = image.NewRGBA(m1.Bounds()) for y := 0; y < m.Bounds().Dy(); y++ { for x := 0; x < m.Bounds().Dx(); x++ { m.Set(x, y, m1.At(x, y)) } } //获取字体 fontBytes, err := ioutil.ReadFile("outimingxi.ttf") if err != nil { log.Println(err) } font, err := freetype.ParseFont(fontBytes) if err != nil { log.Println(err) } //设置字体 f := freetype.NewContext() f.SetDPI(72) f.SetFont(font) f.SetFontSize(36) f.SetClip(m1.Bounds()) f.SetDst(m) f.SetSrc(image.NewUniform(color.RGBA{0, 255, 0, 255})) //开始绘制 draw.Draw(m, m1.Bounds(), m1, image.ZP, draw.Src) pt := freetype.Pt(m.Bounds().Dx()-300, m.Bounds().Dy()-12) _, err = f.DrawString("2019-11-28 lalala", pt) // Rect(100, 100, 800, 800) gc := draw2dimg.NewGraphicContext(m) gc.SetStrokeColor(color.RGBA{0, 255, 0, 0xff}) gc.SetFillColor(color.RGBA{0, 0, 0, 0}) gc.SetLineWidth(5) gc.BeginPath() gc.MoveTo(80, 80) gc.LineTo(800, 80) gc.LineTo(800, 800) gc.LineTo(80, 800) gc.LineTo(80, 80) gc.Close() gc.FillStroke() //写入新文件 err = jpeg.Encode(f3, m, &jpeg.Options{90}) if err != nil { panic(err) } fmt.Printf("ok\n") }
#1