/**
* @author :jerry
* @date :Created in 2022/4/20 16:37
* @description:图片中写文字
* @version: V1.1
*/
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.StringJoiner;
/**
* @use 利用Java代码给图片加水印
*/
public class Graphics2DUtils {
/**
* @param waterMarkContent 水印内容
* Linxu中要加字体:
*/
public void addWaterMark(String waterMarkContent, String fileName, int y, String srcImgPath) {
// 存库的文件名
String tarImgPath = Paths.get("upload").toAbsolutePath().toString() + "/" + fileName + ".jpg";
Font font = new Font("微软雅黑", Font.PLAIN, 25); //水印字体
//水印图片色彩以及 透明度
Color markContentColor = new Color(0, 0, 0, 255); //水印颜色
try {
// 读取原图片信息
//得到文件
File srcImgFile = new File(srcImgPath);
//文件转化为图片
Image srcImg = ImageIO.read(srcImgFile);
//获取图片的宽
int srcImgWidth = srcImg.getWidth(null);
//获取图片的高
int srcImgHeight = srcImg.getHeight(null);
// 加水印
BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bufImg.createGraphics();
g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
//根据图片的背景设置水印颜色
g.setColor(markContentColor);
//设置字体
g.setFont(font);
//设置水印的坐标
int x = 140;
// int y = 100;
//画出水印
g.drawString(waterMarkContent, x, y);
g.dispose();
// 输出图片
FileOutputStream outImgStream = new FileOutputStream(tarImgPath);
ImageIO.write(bufImg, "jpg", outImgStream);
System.out.println("添加水印完成");
outImgStream.flush();
outImgStream.close();
} catch (Exception e) {
e.getMessage();
// TODO: handle exception
}
}
public int getWatermarkLength(String waterMarkContent, Graphics2D g) {
return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());
}
public static void main(String[] args) {
//todo 模版文件路径
String srcImgPath = Paths.get("upload").toAbsolutePath().toString() + "/fileName_template.jpg";
String openId="o71E55v6okf_T4OQPAqtEku45";
String filename = openId;
// StringJoiner result = new StringJoiner("\r\n");
ArrayList<String> lis = new ArrayList<>();
lis.add("姓名:jerry");
lis.add("身份证号:" + "11372119940709067X");
lis.add("公司名:" + "北京好利数据有限公司");
int y=565;
for (int i = 0; i < lis.size(); i++) {
y+=92;
if(i>0){
srcImgPath= Paths.get("upload/").toAbsolutePath().toString()+ "/"+openId+".jpg";
// srcImgPath= Paths.get("upload").toAbsolutePath().toString() +"/filename.jpg";
}
new Graphics2DUtils().addWaterMark(lis.get(i), filename,y,srcImgPath);
}
}
}
注意:(fileName_template.jpg为模版文件,可以自选)
Linux环境部署时中文乱码解决方案:
?1.检查服务器是否有对应字体
fc-list :lang=zh?
2.如果没有则安装:
安装字体库:
yum -y install fontconfig
3.从windwos系统中C:\Windows\Fonts目录下找到simsun.ttc文件,并copy到linux服务器/usr/share/fonts/chinese,chinese是自己新建的文件夹
- 执行命令修改权限
-
chmod 777 simsun.ttc
4.修改字体配置文件vim?/etc/fonts/fonts.conf,添加<dir>/usr/share/fonts/chinese</dir>
5.保存后输入fc-cache,这样不需要重启服务器
?6.最好输入fc-list :lang=zh,配置成功
?
|