package cn.com.wasec.eac.utils;
import java.util.Date;
import cn.com.wasec.eac.model.param.ReceiptInfoParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
@Slf4j
public class WaterMarkUtil {
public static void addWaterMark(String tarImgPath, ReceiptInfoParam receiptInfoParam, Color markContentColor, Font font){
try {
//获取图片
ClassPathResource classPathResource = new ClassPathResource("static/image/receipt.jpg");
File srcImgFile = classPathResource.getFile();
Image srcImg = ImageIO.read(srcImgFile);
int srcImgWidth = srcImg.getWidth(null);
int srcImgHeight = srcImg.getHeight(null);
//加水印
BufferedImage bufferedImage = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = bufferedImage.createGraphics();
graphics.drawImage(srcImg, 0,0 , srcImgWidth, srcImgHeight, null);
graphics.setColor(markContentColor);
graphics.setFont(font);
//设置水印坐标位置
int x = 80;
int y = 200;
graphics.drawString("单位: " + receiptInfoParam.getUnit(), x, y);
graphics.drawString("编号: " + receiptInfoParam.getReceipt(), x, y+20);
graphics.drawString("时间: " + receiptInfoParam.getCreateTime(), x, y+40);
graphics.drawString("类型: " + receiptInfoParam.getType(), x, y+60);
graphics.drawString("姓名: " + receiptInfoParam.getFullName(), x, y+80);
graphics.drawString("号码: " + receiptInfoParam.getMobile(), x, y+100);
graphics.drawString("名称: " + receiptInfoParam.getReceiptName(), x, y+120);
graphics.drawString("Hash值: " + receiptInfoParam.getReceiptHash(), x, y+140);
graphics.drawString("时间: " + receiptInfoParam.getSendTime(), x, y+160);
graphics.drawString("时间: " + receiptInfoParam.getArriveTime(), x, y+180);
graphics.drawString("结果: " + receiptInfoParam.getArriveResult(), x, y+200);
// Field[] fields = receiptInfoParam.getClass().getDeclaredFields();
// for(Field s:fields){
// y += 20;
// System.out.println(s.getName());
// graphics.drawString(s.getName()+" ", x, y);
//
// }
//说明内容
graphics.drawString("说明:", x, 520);
graphics.drawString("1、", x, 540);
graphics.drawString("2、", x, 560);
graphics.drawString(" ", x, 580);
//graphics.drawString("内容", x, y);
//graphics.drawString("新的数据", x, 300);
graphics.dispose();
//输出新图片
File file = new File(tarImgPath);
if (!file.getParentFile().exists()) {
if (!file.getParentFile().mkdirs()) {
log.warn("创建文件夹失败!");
}
}
FileOutputStream fileOutputStream = new FileOutputStream(tarImgPath);
ImageIO.write(bufferedImage, "jpg", fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
}catch (Exception e){
e.printStackTrace();
}
}
public static void receipt(ReceiptInfoParam receiptInfoParam, String tarImgPath){
Font font = new Font("微软雅黑", Font.PLAIN, 12);
Color color = new Color(0,0,0,128); //水印图片色彩以及透明度
addWaterMark(tarImgPath, receiptInfoParam, color, font);
}
}
图片加水印
于 2022-02-21 13:56:54 首次发布