PHP中高级工程师面试重点讲解视频课程
Go快速入门浅显易懂视频教程-基础篇
Go快速入门浅显易懂视频教程-中级篇
go给图片添加文字
阅读:3089 分享次数:0

package main

import (
    "flag"
    "image"
    "image/draw"
    "image/jpeg"
    "io/ioutil"
    "log"
    "os"

    "github.com/golang/freetype"
    "golang.org/x/image/font"
)

var (
    dpi      = flag.Float64("dpi", 72, "screen resolution in Dots Per Inch")
    fontfile = flag.String("fontfile", "luxisr.ttf", "filename of the ttf font")
    hinting  = flag.String("hinting", "none", "none | full")
    size     = flag.Float64("size", 12, "font size in points")
    spacing  = flag.Float64("spacing", 1.5, "line spacing (e.g. 2 means double spaced)")
    wonb     = flag.Bool("whiteonblack", false, "white text on a black background")
)

var text = []string{
    "33333333333333333",
}

func main() {
    flag.Parse()

    //读取字体
    fontBytes, err := ioutil.ReadFile(*fontfile)
    if err != nil {
        log.Println(err)
        return
    }
    //解析字体
    f, err := freetype.ParseFont(fontBytes)
    if err != nil {
        log.Println(err)
        return
    }

    // 初始化图片背景
    fg := image.Black

    if *wonb {
        fg = image.White
    }
    //初始化一张图片,生成原图
    imgB, _ := os.Open("a.jpg")
    img, _ := jpeg.Decode(imgB)
    defer imgB.Close()
    b := img.Bounds()
    rgba := image.NewNRGBA(b)
    draw.Draw(rgba, rgba.Bounds(), img, image.ZP, draw.Src)

    //在图片上面添加文字
    c := freetype.NewContext()
    c.SetDPI(*dpi)
    //设置字体
    c.SetFont(f)
    //设置大小
    c.SetFontSize(*size)
    //设置边界
    c.SetClip(rgba.Bounds())
    //设置背景底图
    c.SetDst(rgba)
    //设置背景图
    c.SetSrc(fg)
    //设置提示
    switch *hinting {
    default:
        c.SetHinting(font.HintingNone)
    case "full":
        c.SetHinting(font.HintingFull)
    }

    // 画文字
    pt := freetype.Pt(10, 10+int(c.PointToFixed(*size)>>6))
    for _, s := range text {
        _, err = c.DrawString(s, pt)
        if err != nil {
            log.Println(err)
            return
        }
        pt.Y += c.PointToFixed(*size * *spacing)
    }

    imgw, _ := os.Create("out.jpg")
    jpeg.Encode(imgw, rgba, &jpeg.Options{100})
    defer imgw.Close()
}

感觉本站内容不错,读后有收获?