用golang 实现给图片添加文字水印

Go 复制代码
package main

import (
	"fmt"
	"github.com/golang/freetype"
	"image"
	"image/draw"
	"image/jpeg"
	"io"
	"os"
	"time"
)

func main() {
	// 打开原始图片
	file, err := os.Open("004.jpeg")
	if err != nil {
		panic(err)
	}
	defer file.Close()

	// 解码图片
	img, _, err := image.Decode(file)
	if err != nil {
		panic(err)
	}

	// 创建一个画布
	bounds := img.Bounds()
	canvas := image.NewRGBA(bounds)


	// 打开图像文件
	fileInfo, err := os.Stat("004.jpeg")
	if err != nil {
		 fmt.Sprintf("无法获取文件信息:%v", err)
	}
	fmt.Println("文件名:",fileInfo.Name())

	//添加该行问题解决
	file.Seek(0, io.SeekStart)

	// 读取图像信息
	config, _, err := image.DecodeConfig(file)
	if err != nil {
		fmt.Println("无法读取图像配置", err)
	}
	width := config.Width
	height := config.Height
	fmt.Println("图片宽度为:", width)
	fmt.Println("图片高度为:", height)
	//s,err:=file.Stat()
	//fmt.Println(file.Name(),s.Size(),s.Sys(),s.Mode(),s.ModTime())

	// 绘制原始图片到画布上
	draw.Draw(canvas, bounds, img, image.Point{}, draw.Src)

	// 添加文字
	fontBytes, err := os.ReadFile("../ttf/kaiti.TTF") //解析中文
	//fontBytes, err := os.ReadFile("../ttf/luxisr.ttf") //不解析中文
	if err != nil {
		panic(err)
	}
	font, err := freetype.ParseFont(fontBytes)
	if err != nil {
		panic(err)
	}

	context := freetype.NewContext()
	context.SetDPI(72)
	context.SetFont(font)
	context.SetFontSize(25)
	context.SetClip(bounds)
	context.SetDst(canvas)
	context.SetSrc(image.Opaque)

	//pt := freetype.Pt(0, 5+int(context.PointToFixed(24)>>6))
	pt := freetype.Pt(250, height-34+int(context.PointToFixed(24)>>6)) //距离左侧5,距离顶部height-34=960-34=926
	context.DrawString("来源公众号:【码农编程进阶笔记】", pt)

	// 保存处理后的图片
	filename := fmt.Sprintf("output_%d.jpg", time.Now().Unix())
	output, err := os.Create(filename)
	if err != nil {
		panic(err)
	}
	defer output.Close()

	// 编码保存到文件
	jpeg.Encode(output, canvas, nil)
}

效果图:

相关推荐
让我们一起加油好吗12 分钟前
【基础算法】枚举(普通枚举、二进制枚举)
开发语言·c++·算法·二进制·枚举·位运算
大锦终12 分钟前
【C++】特殊类设计
开发语言·c++
朱龙凯14 分钟前
MySQL那些事
后端
Re27521 分钟前
剖析 MyBatis 延迟加载底层原理(1)
后端·面试
Victor35624 分钟前
MySQL(63)如何进行数据库读写分离?
后端
Cache技术分享25 分钟前
99. Java 继承(Inheritance)
前端·后端
M1A127 分钟前
Python数据结构操作:全面解析与实践
后端·python
程序员蜗牛27 分钟前
Controller层代码瘦身70%!5招打通任督二脉,效率飙升
后端
程序员岳焱29 分钟前
Java高级反射实战:15个场景化编程技巧与底层原理解析
java·后端·编程语言
程序员小假29 分钟前
说一说 Netty 中的心跳机制
java·后端