ZBLOG

golang 图片加文字生成新的图片

下面是一个示例代码,使用 Go 语言将文字添加到图片中并生成新的图片。

package main

import (
    "fmt"
    "image"
    "image/color"
    "image/draw"
    "image/font"
    "image/jpeg"
    "os"

    "golang.org/x/image/font/basicfont"
)

func main() {
    file, err := os.Open("input.jpg")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer file.Close()

    img, _, err := image.Decode(file)
    if err != nil {
        fmt.Println(err)
        return
    }

    // 创建一个带有文本的新图像
    textImg := image.NewRGBA(img.Bounds())
    draw.Draw(textImg, textImg.Bounds(), img, image.Point{}, draw.Src)

    c := freetype.NewContext()
    c.SetDst(textImg)
    c.SetSrc(image.White)
    c.SetHinting(font.HintingNone)

    // 使用基础字体
    fontFace := basicfont.Face7x13
    fontSize := 20.0

    // 添加文本到图像上
    pt := freetype.Pt(10, 50+int(c.PointToFixed(fontSize)>>6))
    _, err = c.DrawString("Hello World!", pt, fontFace, &truetype.Options{
        Size:    fontSize,
        DPI:     72,
        Hinting: font.HintingFull,
    })
    if err != nil {
        fmt.Println(err)
        return
    }

    // 将带有文本的图像保存为 JPEG 格式
    outputFile, err := os.Create("output.jpg")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer outputFile.Close()

    jpeg.Encode(outputFile, textImg, &jpeg.Options{Quality: 100})
}

在这个示例代码中,我们首先打开了一个 JPEG 图像文件。然后,使用 image.Decode() 函数来解码该图像并获取其像素数据。

接下来,我们通过 image.NewRGBA() 函数创建了一个新的 RGBA 图像,并用 draw.Draw() 函数将原始图像复制到新图像上。这将保留原始图像中的所有像素数据,但不会修改它。

然后,我们创建了一个 freetype.Context 对象,并设置其相关属性,例如绘制目标、源和字体等。使用 basicfont.Face7x13 字体和字号为 20,在图像上添加了一个文本字符串“Hello World!”。使用 freetype.Pt() 函数来指定文本位置。

最后,我们使用 jpeg.Encode() 函数将带有文本的图像保存为 JPEG 格式,并写入输出文件中。

在运行示例代码之前,请确保您已安装必要的库和软件包,例如 golang.org/x/image/fontgolang.org/x/image/font/basicfont 等。

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=235

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?