Golang 圖片上繪製文字

以前介紹過使用 FreeType-go 來繪製字(http://www.cnblogs.com/ghj1976/p/3445568.html),  如今相關的包被作了整合,主要是整合到了 github.com/golang/freetype 和 golang.org/x/image/font 這裏了,因此就有了這篇博客。html

 

例子代碼在: https://github.com/golang/freetype/blob/master/example/freetype/main.gogit

 

package maingithub

import (
    "bufio"
    "flag"
    "fmt"
    "image"
    "image/color"
    "image/draw"
    "image/png"
    "io/ioutil"
    "log"
    "os"golang

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

var (
    dpi      = flag.Float64("dpi", 72, "screen resolution in Dots Per Inch")
    fontfile = flag.String("fontfile", "../../testdata/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{
    "’Twas brillig, and the slithy toves",
    "測試中文字 ……&^_^",
    "Did gyre and gimble in the wabe;",
    "All mimsy were the borogoves,",
    "And the mome raths outgrabe.",
    "",
    "「Beware the Jabberwock, my son!",
    "The jaws that bite, the claws that catch!",
    "Beware the Jubjub bird, and shun",
    "The frumious Bandersnatch!」",
    "",
    "He took his vorpal sword in hand:",
    "Long time the manxome foe he sought—",
    "So rested he by the Tumtum tree,",
    "And stood awhile in thought.",
    "",
    "And as in uffish thought he stood,",
    "The Jabberwock, with eyes of flame,",
    "Came whiffling through the tulgey wood,",
    "And burbled as it came!",
    "",
    "One, two! One, two! and through and through",
    "The vorpal blade went snicker-snack!",
    "He left it dead, and with its head",
    "He went galumphing back.",
    "",
    "「And hast thou slain the Jabberwock?",
    "Come to my arms, my beamish boy!",
    "O frabjous day! Callooh! Callay!」",
    "He chortled in his joy.",
    "",
    "’Twas brillig, and the slithy toves",
    "Did gyre and gimble in the wabe;",
    "All mimsy were the borogoves,",
    "And the mome raths outgrabe.",
}字體

func main() {
    flag.Parse()ui

    // Read the font data.
    fontBytes, err := ioutil.ReadFile(*fontfile)
    if err != nil {
        log.Println(err)
        return
    }
    f, err := freetype.ParseFont(fontBytes)
    if err != nil {
        log.Println(err)
        return
    }spa

    // Initialize the context.
    fg, bg := image.Black, image.White
    ruler := color.RGBA{0xdd, 0xdd, 0xdd, 0xff}
    if *wonb {
        fg, bg = image.White, image.Black
        ruler = color.RGBA{0x22, 0x22, 0x22, 0xff}
    }
    rgba := image.NewRGBA(image.Rect(0, 0, 640, 480))
    draw.Draw(rgba, rgba.Bounds(), bg, 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)
    }rest

    // Draw the guidelines.
    for i := 0; i < 200; i++ {
        rgba.Set(10, 10+i, ruler)
        rgba.Set(10+i, 10, ruler)
    }

    // Draw the text.
    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)
    }

    // Save that RGBA image to disk.
    outFile, err := os.Create("out.png")
    if err != nil {
        log.Println(err)
        os.Exit(1)
    }
    defer outFile.Close()
    b := bufio.NewWriter(outFile)
    err = png.Encode(b, rgba)
    if err != nil {
        log.Println(err)
        os.Exit(1)
    }
    err = b.Flush()
    if err != nil {
        log.Println(err)
        os.Exit(1)
    }
    fmt.Println("Wrote out.png OK.")
}

執行效果以下:

./testFont2 -fontfile="字體管家淘淘體.ttf"

執行效果:

image

./testFont2 -fontfile="6f14c8f349377d5ebe2b0a5e2851a6f6.ttf"

執行效果:

image

./testFont2 -fontfile="Sliced by Hand.ttf"

執行效果,這個字體不支持中文,就會出現下面狀況:

image

 

 

 

一些免費的字體庫下載

英文字體庫

http://www.freefontspro.com/cn/

http://cn.fontriver.com/ 

中文字體庫

http://fonts.mobanwang.com/ 

http://www.touwenzi.com/

相關文章
相關標籤/搜索