zoukankan      html  css  js  c++  java
  • golang——image库图片上写字

    package main
    
    import (
    	"github.com/golang/freetype"
    	"image"
    	"image/color"
    	"image/png"
    	"io/ioutil"
    	"log"
    	"os"
    )
    
    func main() {
    	//图片的宽度
    	srcWidth := 200
    	//图片的高度
    	srcHeight := 200
    	imgfile, _ := os.Create("out.png")
    	defer imgfile.Close()
    
    	img := image.NewRGBA(image.Rect(0, 0, srcWidth, srcHeight))
    
    	//为背景图片设置颜色
    	for y := 0; y < srcWidth; y++ {
    		for x := 0; x < srcHeight; x++ {
    			img.Set(x, y, color.RGBA{255, 255, 255, 255})
    		}
    	}
    
    	//读取字体数据  http://fonts.mobanwang.com/201503/12436.html
    	fontBytes, err := ioutil.ReadFile("./public/xiawucha.ttf")
    	if err != nil {
    		log.Println(err)
    	}
    	//载入字体数据
    	font, err := freetype.ParseFont(fontBytes)
    	if err != nil {
    		log.Println("载入字体失败", err)
    	}
    	f := freetype.NewContext()
    	//设置分辨率
    	f.SetDPI(100)
    	//设置字体
    	f.SetFont(font)
    	//设置尺寸
    	f.SetFontSize(26)
    	f.SetClip(img.Bounds())
    	//设置输出的图片
    	f.SetDst(img)
    	//设置字体颜色(红色)
    	f.SetSrc(image.NewUniform(color.RGBA{255, 0, 0, 255}))
    
    	//设置字体的位置
    	pt := freetype.Pt(20, 40)
    
    	_, err = f.DrawString("hello,你好", pt)
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	//以png 格式写入文件
    	err = png.Encode(imgfile, img)
    	if err != nil {
    		log.Fatal(err)
    	}
    }
    

      

  • 相关阅读:
    linux查看进程命令
    linux修改时区的命令
    深度学习VGG16模型核心模块拆解
    Python之format()函数
    os.path.isfile()的正确用法(正确用法)
    Python time.time()方法
    tf.train.Saver()
    Python3字典update()方法
    图解Numpy的tile函数
    池化层的作用和种类
  • 原文地址:https://www.cnblogs.com/itsuibi/p/14704193.html
Copyright © 2011-2022 走看看