Golang Gin Practice Serialization 16 Draw Text on Pictures

  fonts, golang, mysql, php

Golang Gin Practice Serialization 16 Draw Text on Pictures

Original address:Golang Gin Practice Serialization 16 Draw Text on Pictures
Project address:go-gin-example


This chapter isSerial 15It is recommended to eat together. Main realizationDraw text on the merged posterThe function of the (this requirement is also very common), the content is relatively simple


What is used here isMicrosoft yaheiPlease click to download andStore in runtime/fonts directoryBelow (font file size 16 MB)


$ go get -u github.com/golang/freetype

Draw text

Open the service/article _ service/article _ poster.go file and add the business logic for drawing text, as follows:

type DrawText struct {
    JPG    draw.Image
    Merged *os.File

    Title string
    X0    int
    Y0    int
    Size0 float64

    SubTitle string
    X1       int
    Y1       int
    Size1    float64

func (a *ArticlePosterBg) DrawPoster(d *DrawText, fontName string) error {
    fontSource := setting.AppSetting.RuntimeRootPath + setting.AppSetting.FontSavePath + fontName
    fontSourceBytes, err := ioutil.ReadFile(fontSource)
    if err != nil {
        return err

    trueTypeFont, err := freetype.ParseFont(fontSourceBytes)
    if err != nil {
        return err

    fc := freetype.NewContext()

    pt := freetype.Pt(d.X0, d.Y0)
    _, err = fc.DrawString(d.Title, pt)
    if err != nil {
        return err

    _, err = fc.DrawString(d.SubTitle, freetype.Pt(d.X1, d.Y1))
    if err != nil {
        return err

    err = jpeg.Encode(d.Merged, d.JPG, nil)
    if err != nil {
        return err

    return nil

The freetype package is mainly used here, involving the following details:

1. freetype.NewContext: Create a new Context and set some default values for it

func NewContext() *Context {
    return &Context{
        r:        raster.NewRasterizer(0, 0),
        fontSize: 12,
        dpi:      72,
        scale:    12 << 6,

2. fc.SetDPI: sets the resolution of the screen per inch

3. fc.SetFont: sets the font used to draw text.

4. fc.SetFontSize: set font size in points

5. fc.SetClip: set clipping rectangle to draw

6. fc.SetDst: set target image

7. fc.SetSrc: sets the source image of the drawing operation, usuallyimage.Uniform

var (
        // Black is an opaque black uniform image.
        Black = NewUniform(color.Black)
        // White is an opaque white uniform image.
        White = NewUniform(color.White)
        // Transparent is a fully transparent uniform image.
        Transparent = NewUniform(color.Transparent)
        // Opaque is a fully opaque uniform image.
        Opaque = NewUniform(color.Opaque)

8. fc.DrawString: Draw the given text content according to the coordinate values of Pt

Business logic

Open the service/article _ service/article _ poster.go method and add the code logic for drawing text in the Generate method, as follows:

func (a *ArticlePosterBg) Generate() (string, string, error) {
    fullPath := qrcode.GetQrCodeFullPath()
    fileName, path, err := a.Qr.Encode(fullPath)
    if err != nil {
        return "", "", err

    if !a.CheckMergedImage(path) {

        draw.Draw(jpg, jpg.Bounds(), bgImage, bgImage.Bounds().Min, draw.Over)
        draw.Draw(jpg, jpg.Bounds(), qrImage, qrImage.Bounds().Min.Sub(image.Pt(a.Pt.X, a.Pt.Y)), draw.Over)

        err = a.DrawPoster(&DrawText{
            JPG:    jpg,
            Merged: mergedF,

            Title: "Golang Gin 系列文章",
            X0:    80,
            Y0:    160,
            Size0: 42,

            SubTitle: "---煎鱼",
            X1:       320,
            Y1:       220,
            Size1:    36,
        }, "msyhbd.ttc")

        if err != nil {
            return "", "", err

    return fileName, path, nil


Access the interface that generates the article poster$HOST/api/v1/articles/poster/generate? token=$token, check the generated results, as shown in the figure below



In this chapter inSerial 15On the basis of the above, drawing text is added, which is not difficult to implement. However, these two requirements usually appear at the same time. You can practice more to understand the logic and other API inside.


This series of sample codes

This series of catalogues