How to add a simple text label to an image in Go?

后端 未结 2 1374
醉话见心
醉话见心 2020-12-07 21:00

Given image.RGBA, coordinates, and a line of text, how do I add a simple label with any plain fixed font? E.g. Face7x13 from font/basicfont.

<
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-07 21:05

    here is the sample code using gg library where we already have src.jpg or any image and we write text over it.. you can adjust canvas size accordingly .. it's just example. let me know if it doesn't work.

    package main
    
    import (
        "github.com/fogleman/gg"
        "log"
    )
    
    func main() {
        const S = 1024
        im, err := gg.LoadImage("src.jpg")
        if err != nil {
            log.Fatal(err)
        }
    
        dc := gg.NewContext(S, S)
        dc.SetRGB(1, 1, 1)
        dc.Clear()
        dc.SetRGB(0, 0, 0)
        if err := dc.LoadFontFace("/Library/Fonts/Arial.ttf", 96); err != nil {
            panic(err)
        }
        dc.DrawStringAnchored("Hello, world!", S/2, S/2, 0.5, 0.5)
    
        dc.DrawRoundedRectangle(0, 0, 512, 512, 0)
        dc.DrawImage(im, 0, 0)
        dc.DrawStringAnchored("Hello, world!", S/2, S/2, 0.5, 0.5)
        dc.Clip()
        dc.SavePNG("out.png")
    }
    

提交回复
热议问题