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

效果图:

相关推荐
Nerd(BUG版)4 分钟前
KMP学习day5--Kotlin Flow异步流基础
开发语言·学习·kotlin
IT_陈寒11 分钟前
SpringBoot实战技巧总结
前端·人工智能·后端
TeamDev15 分钟前
使用 JxBrowser 在桌面应用中集成 Spring
java·前端·后端·spring·混合应用·jxbrowser·浏览器控件
J.YA22 分钟前
String字符串[面试题]
java·开发语言
量化分析码农1 小时前
【Python量化多因子实战 05】因子也会轮动:因子动量与因子反转的择时应用
后端
陈随易1 小时前
Rolldown 把插件改动回传提速 26 倍
前端·后端·程序员
金銀銅鐵10 小时前
为什么枚举类中可以定义抽象方法
java·后端·ai编程
陈随易10 小时前
Vue 编译器换掉 source map,快了三四成
前端·后端·程序员
xiaoye-duck11 小时前
《C++ 项目:手写大模型接入 SDK》Gemini接口设计(上):初始化、全量响应实现和测试
开发语言·网络·c++·语言模型
txxzjmzlh12 小时前
SpringBoot 统⼀功能处理
java·spring boot·后端