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

效果图:

相关推荐
honder试试3 小时前
焊接自动化测试平台图像处理分析-模型训练推理
开发语言·python
^Rocky3 小时前
JavaScript性能优化实战
开发语言·javascript·性能优化
ponnylv3 小时前
深入剖析Spring Boot启动流程
java·开发语言·spring boot·spring
萧邀人3 小时前
第一课、Cocos Creator 3.8 安装与配置
开发语言
YGGP3 小时前
3D 版接雨水
golang
Jayden_Ruan4 小时前
C++逆向输出一个字符串(三)
开发语言·c++·算法
不吃鱼的羊4 小时前
启动文件Startup_vle.c
c语言·开发语言
cyforkk4 小时前
Spring Boot @RestController 注解详解
java·spring boot·后端
VBA63374 小时前
VBA之Word应用第四章第二节:段落集合Paragraphs对象(二)
开发语言