需求描述

自己在写技术博客需要一个图片来作为文章的封面, 由于懒惰和时间成本没有开发这项功能. 在对接 web 端以及小程序端都需要封面图来撑起来大大的版面怎么办, 那么这个 text2img的扩展包就起作用了, 它能用指定的文本来生成固定格式的图片. 效果如下:

https://www.mirchen.com/img/5.jpg

好, 那我们现在开始吧.

命令行使用

扩展地址: https://github.com/Iwark/text2img.git

该项目支持命令和开发包源码方式使用, 以下逐一介绍

二进制文件下载

可以到https://github.com/Iwark/text2img/releases来下载官方发行的二进制包.

或者使用命令:

go get github.com/Iwark/text2img/cmd/text2img

这种方式直接可以将二进制文件添加到环境变量中进行使用:

# 基本使用
$ text2img -h
Usage of text2img:
  -bgimg string
    	path to the background image 	#背景图, 如不设置则随机生成一个背景色
  -fontpath string	
    	path to the font	#要生成图片字体使用的字体路径
  -output string
    	path to the output image (default "image.jpg")	#输出图片名称
  -text string
    	text to draw	#文字内容

我们要生成随机背景颜色的图片:

$ text2img -fontpath="fonts/font.ttf" -output="test.jpg" -text="text2img generates the image from a text"

我们要生成指定背景图片和指定内容的图片,我们可以使用下面的命令:

$ text2img -fontpath="fonts/font.ttf" -output="test.jpg" -text="text2img generates the image from a text" -bgimg="gophers.jpg"

以上是命令行的基本用法.

GO 代码

使用命令下载第三方包

go get -v go get github.com/Iwark/text2img

在我们项目中可能这样使用:

package main

import (
  "image/jpeg"
  "os"

  "github.com/Iwark/text2img"
)

func Text2Img(name, str string) error {
	workingDir, _ := os.Getwd()
	f, err := os.Open(workingDir + "/" + name)
	if os.IsExist(err) {
		return nil
	}
	f.Close()
	path := workingDir + "/public/font/WeiRuanYaHei.ttf"
	d, err := text2img.NewDrawer(text2img.Params{
		FontPath: path,
	})
	if err != nil {
		return err
	}
	img, err := d.Draw(str)
	if err != nil {
		return err
	}
	file, err := os.Create(workingDir + "/" + name)
	if err != nil {
		return err
	}
	defer file.Close()
	return jpeg.Encode(file, img, &jpeg.Options{Quality: 100})
}

func main (){
    err := Text2Img("mypic.png", "Hello Gin Web Developer")
    if err != nil {
        painc(err)
    }
}

这样我们就可以在我们项目图片中使用起来, 随意切换封面图是否上传还是自动生成.

虽然这个功能很简单,但是比较实用, 平时自己做功能的时候一般不会考虑到类似这样的需求. 在自己小程序中发现如果没有图片封面闲的很空洞, 所以在这里做一下记录.