首页 > 其他分享 >Golang 图片上绘制文字

Golang 图片上绘制文字

时间:2023-06-21 21:03:33浏览次数:50  
标签:err image Golang flag rgba Println font 绘制 图片

之前介绍过使用 FreeType-go 来绘制字 现在相关的包被做了整合,主要是整合到了 github.com/golang/freetype 和 golang.org/x/image/font 这里了,所以就有了这篇博客。

 

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

 

package main
import (     
    "bufio"      
    "flag"      
    "fmt"      
    "image"      
    "image/color"      
    "image/draw"      
    "image/png"      
    "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", "../../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()    // 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      
    }    // 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)      
    }    // 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"

执行效果:

Golang 图片上绘制文字_ci

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

执行效果:

Golang 图片上绘制文字_ci_02

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

执行效果,这个字体不支持中文,就会出现下面情况:

Golang 图片上绘制文字_github_03

 

 

 

一些免费的字体库下载

英文字体库

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

http://cn.fontriver.com/ 

中文字体库

http://fonts.mobanwang.com/ 

http://www.touwenzi.com/

标签:err,image,Golang,flag,rgba,Println,font,绘制,图片
From: https://blog.51cto.com/u_15588078/6531418

相关文章

  • Mac下如何复制webp图片
     将WebP格式图片拖到Chrome浏览器标签栏中(浏览器是肯定支持查看的,而且是Google自家的),这个时候图片是能够正常查看的。我们右键选中图片,选择「复制图片」。打开macOS系统自带的「预览」工具,点击菜单栏「文件」,选中「从剪贴板新建」,这时候图片就显示在「预览」工具的窗口中......
  • Perfectly Clear Workbench(图片编辑软件)mac/win
    PerfectlyClearWorkBench是一款由AthentechImaging开发的图像校正软件,它提供了高效、自动化的图像颜色和曝光校正工具。该软件可以使用各种算法对图像进行智能分析和处理,以确保最佳视觉结果。Mac版PerfectlyClearWorkbench下载Win版PerfectlyClearWorkbench中文版Perfe......
  • C# 图片转PDF,PDF增加水印文字
    好久没写博客了,今天给大家分享一个图片转PDF的相关操作,也算是一次总结吧。首先需要准备动态库itextsharp.dll,这个dll去网上下载,都可以下载到,C#对PDF的操作都是基于这个类库来实现的。话不多说,直接上代码。///<summary>///导出PDF///</sum......
  • app直播源代码,Android中点击图片放大的简单方法
    app直播源代码,Android中点击图片放大的简单方法Java代码: publicvoidonThumbnailClick(Viewv){//finalAlertDialogdialog=newAlertDialog.Builder(this).create();//ImageViewimgView=getView();//dialog.setView(imgView);//dialog.show();  //全屏显示的......
  • 前端JS zip打包文件并下载,图片url转base64
    使用jszip这个项目实现的:https://github.com/Stuk/jszipFileSaver.js项目地址是:https://github.com/eligrey/FileSaver.js/<scriptsrc="./FileSaver.min.js"></script><scriptsrc="./jszip.min.js"></script>//初始化一个zip打包对象varzi......
  • Golang 中文转拼音
    翻遍整个GitHub,Golang中文转拼音类库,怎么就这么难找呢?于是我造了一个轮子:中文转拼音类库.目前来说应该是最好用的了.GitHub传送门:https://github.com/Lofanmi/pinyin-golang如果说基于汉字拼音字典,逐个汉字替换,也是可以转换的,但是碰到多音字就很麻烦了.而......
  • 显示图片一部分
    //SetsomeconstantsprivatestaticfinalBitmapSOURCE_BITMAP=BitmapFactory.decodeFile(....);//GetthesourceBitmapusingyourfavoritemethod:-)privatestaticfinalintSTART_X=10;privatestaticfinalintSTART_Y=15;privatestaticfina......
  • 富文本编辑器从word复制粘贴图片
    ​ 当前功能基于PHP,其它语言流程大致相同 1.新增上传wordjson配置在ueditor\php\config.json中新增如下配置:     /* 上传word配置 */    "wordActionName":"wordupload",/* 执行上传视频的action名称 */    "wordFieldName":"upfile",/* 提交的......
  • 记录--前端实现文件预览(pdf、excel、word、图片)
    这里给大家分享我在网上总结出来的一些知识,希望对大家有所帮助前端实现文件预览功能需求:实现一个在线预览pdf、excel、word、图片等文件的功能。介绍:支持pdf、xlsx、docx、jpg、png、jpeg。以下使用Vue3代码实现所有功能,建议以下的预览文件标签可以在外层包裹一层弹窗。......
  • Web编辑器从word复制粘贴图片
    ​图片的复制无非有两种方法,一种是图片直接上传到服务器,另外一种转换成二进制流的base64码目前限chrome浏览器使用首先以um-editor的二进制流保存为例:打开umeditor.js,找到UM.plugins['autoupload'],然后找到autoUploadHandler方法,注释掉其中的代码。加入下面的代码://判断剪贴......