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)
    	}
    }
    

      

  • 相关阅读:
    求24点
    关于参数和返回值的常量性
    点到平面的距离公式
    大端序与小端序
    Quake3中的绝对值函数
    整数超出范围时如何表示?
    关于数组的几道面试题
    在移位数组中查找数
    时间复杂度O(n),空间复杂度O(1)的排序
    C++之对象切割
  • 原文地址:https://www.cnblogs.com/itsuibi/p/14704193.html
Copyright © 2011-2022 走看看