package com.tgpms.utils;
import cn.hutool.core.util.StrUtil;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
/**
* 图片添加水印
*
* @author jiangli
* @since 2021/3/11 8:23
*/
public class WaterMarkUtil {
// 用来调整水印的间距
private static final int space = 20;
/**
*
* @param srcImgFile 待添加水印的图片
* @param outImgPath 添加完成的输出路径
* @param markContentColor 文字颜色
* @param waterMarkContent 水印内容, 需要换行用||连接
*/
public static void drawCaterMark(File srcImgFile, String outImgPath, Color markContentColor, String waterMarkContent) {
try {
String[] waterMarkContents = waterMarkContent.split("\\|\\|");
// 读取原图片信息
// 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);
int fontSize = srcImg.getWidth(null) / 300 * 10;
Font font = new Font("微软雅黑", Font.PLAIN, fontSize);
// 设置水印颜色
g.setColor(markContentColor);
// 设置水印文字字体
g.setFont(font);
// 抗锯齿
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
java.util.List<String> waterMarkContentList = new ArrayList<>();
// 将换行后的文字放入新的集合
for (String markContent : waterMarkContents) {
// 单字符长度
int tempCharLen = 0;
// 单行字符总长度临时计算
int tempLineLen = 0;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < markContent.length(); i++) {
char tempChar = markContent.charAt(i);
tempCharLen = getCharLen(tempChar, g);
tempLineLen += tempCharLen;
// 文字长度大于图片宽度-2*间距-字体大小
if (tempLineLen > srcImgWidth - space * 2 - tempCharLen) {
// 长度已经满一行
waterMarkContentList.add(sb.toString());
// 清空内容,重新追加
sb.delete(0, sb.length());
tempLineLen = 0;
}
// 追加字符
sb.append(tempChar);
}
waterMarkContentList.add(sb.toString());
}
// 绘制水印
int tempY = fontSize + space;
for (int i = 0; i < waterMarkContentList.size(); i++) {
String s = waterMarkContentList.get(i);
//左上角
// g.drawString(s, space, i * tempY + 2 * space);
//右下角
g.drawString(s, space, srcImgHeight - (waterMarkContentList.size() - i) * tempY + space);
}
g.dispose();
// 输出图片
if (StrUtil.isNotBlank(outImgPath)) {
FileOutputStream outImgStream = new FileOutputStream(outImgPath);
ImageIO.write(bufImg, "jpg", outImgStream);
outImgStream.flush();
outImgStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static int getCharLen(char c, Graphics2D g) {
return g.getFontMetrics(g.getFont()).charWidth(c);
}
/**
* 获取水印文字总长度
*
* @param waterMarkContent 水印的文字
* @param g 绘图方法
* @return 水印文字总长度
*/
public static int getWatermarkLength(String waterMarkContent, Graphics2D g) {
return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());
}
}
使用
/**
* 新增新建管网信息管道
*/
@ApiOperation(value = "新增新建管网信息管道", notes = "新增新建管网信息管道", httpMethod = "POST")
@PostMapping(value = "/tofly-sxgk/newpspipe", headers = "content-type=multipart/form-data")
public Result addNewpspipe(@RequestParam(value = "newpspipe") String jsonString,@RequestParam String waterMarkContent, HttpServletRequest request) {
InLineParts inLineParts = JSONUtil.toBean(jsonString, InLineParts.class);
List<MultipartFile> files = new ArrayList<>();
// 获取文件集合
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
if (CollectionUtil.isNotEmpty(fileMap)) {
for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
// 获取单个文件
MultipartFile mf = entity.getValue();
files.add(mf);
}
}
// 临时文件,最后要删除
List<File> images = new ArrayList<>();
try {
// 发送给同飞的参数
Map<String, Object> paramMap = new HashMap<>();
if (CollectionUtil.isNotEmpty(inLineParts.getNewpspipefileList())) {
List<Newpspipefile> newpspipefileList = inLineParts.getNewpspipefileList();
for (int i = 0; i < newpspipefileList.size(); i++) {
Newpspipefile newpspipefile = newpspipefileList.get(i);
paramMap.put("newpspipefileList[" + i + "].fileName", newpspipefile.getFileName());
paramMap.put("newpspipefileList[" + i + "].distance", newpspipefile.getDistance());
paramMap.put("newpspipefileList[" + i + "].latitude", newpspipefile.getLatitude());
paramMap.put("newpspipefileList[" + i + "].longitude", newpspipefile.getLongitude());
paramMap.put("newpspipefileList[" + i + "].sxCoor", newpspipefile.getSxCoor());
paramMap.put("newpspipefileList[" + i + "].syCoor", newpspipefile.getSyCoor());
File image = MultipartFileToFile.multipartFileToFile(files.get(i));
// 添加水印(MultipartFile要转换成File,生成的带水印的图片替换掉原来的临时图片,临时图片最后删除)
CaterMarkUtil.drawCaterMark(image,image.getPath(), Color.red,waterMarkContent);
paramMap.put(newpspipefile.getFileName(), image);
images.add(image);
}
}
// 调用同飞修改接口
paramMap.putAll(BeanUtil.beanToMap(inLineParts, false, true));
paramMap.remove("newpspipefileList");
String token = request.getHeader("tfToken");
String body = HttpRequest.post(PropertiesUtil.HOST + tongFeiUrl.getNewpspipe())
.header(Header.AUTHORIZATION, "Bearer " + token)
.header(Header.CONTENT_TYPE, "multipart/form-data")
.form(paramMap)
.execute().body();
R r = JSON.parseObject(body, R.class);
return CommonMethods.tongFeiResponseToResult(r);
} catch (Exception e) {
e.printStackTrace();
return Result.error(e.getMessage());
} finally {
MultipartFileToFile.delteTempFile(images);
}
}