1

I want to insert text into some template images using golang. One specific requirement is that the unit of the text coordination is by px instead of point.

I've done some searches before I asked this question. This link gave some suggestions, whose core code is:

func addLabel(img *image.RGBA, x, y int, label string) {
    c.SetDst(img)
    size := 12.0 // font size in pixels
    pt := freetype.Pt(x, y+int(c.PointToFixed(size)>>6))

    if _, err := c.DrawString(label, pt); err != nil {
        // handle error
    }
}

As we can see, the only unit option is Point and its odd bit operation (>>6).

However, unit of template data generated by PhotoShop coordinating system is px.

This bothered me a lot that I can not find a perfect way to convert the unit because there is always tiny offset compared with the raw pixel location and size of the offset is determined by the text size. The larger text generates larger offset.

What can I do to insert the text into exactly right pixel location?

ucag
  • 275
  • 1
  • 6
  • 20
  • Font metrics are difficult/specialized. You might consider using a more full-featured low-level image graphics library such as https://github.com/gographics/imagick... – BadZen Jul 24 '21 at 20:44
  • At the bottom on your [link](https://stackoverflow.com/questions/38299930/how-to-add-a-simple-text-label-to-an-image-in-go), there is an example use "github.com/fogleman/gg". I have tried the codes, they work and you may use it. – Chris Wong Jul 25 '21 at 06:45
  • 1
    @BadZen thx bro, I using this lib solved my problem and became one of its contributors. – ucag Aug 06 '21 at 07:37
  • @ChrisWong this is a nice and easy to use lib. but there are still some ambiguous places for this lib to work on. Basically, all font or image lib in `golang`, things to do with `size` like `point size` or `pixel size` are done by `simulating`, especially for font, the lib needs to take care of the font rendering metrics, not only `text height` or `text width` but also `text baseline` or `character metrics` etc, for image, `ppi` and `dpi` conversion and computing is also a problem. For lib you mentioned, which is `gg`, can finish some jobs not requiring absolute accuracy in a very well way. – ucag Aug 06 '21 at 07:45

0 Answers0