废话不多说,直接上代码
@PostMapping("/watermarkImages")
public String watermarkImages() throws Exception {
//获取原始图片文件
String srcImgPath = "F://bg1.png";
String fileNameType = srcImgPath.substring(srcImgPath.lastIndexOf("."), srcImgPath.length());
String tarImgPath = CustomConfig.diskLocation + System.currentTimeMillis() + fileNameType; //待存储的地址
addWaterMark(srcImgPath, tarImgPath);
return "success";
}
/***
* 在一张背景图上添加二维码
* @param bigImgPath 背景图的路径
* @param outPathWithFileName 输出路径
*/
public void addWaterMark(String bigImgPath, String outPathWithFileName) throws Exception {
// 读取原图片信息
File srcImgFile = new File(bigImgPath);//得到文件
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);
String content = "时光蹉跎看淡岁月你我";
//使用工具类生成二维码
Image image = QRCodeUtil.createImages(content);
//将小图片绘到大图片上,500,300 .表示你的小图片在大图片上的位置。
g.drawImage(image, 500, 500, null);
//设置颜色。
g.setColor(Color.WHITE);
g.dispose();
// 输出图片
FileOutputStream outImgStream = new FileOutputStream(outPathWithFileName);
ImageIO.write(bufImg, "png", outImgStream);
System.out.println("添加水印完成");
outImgStream.flush();
outImgStream.close();
}
/***
* 生成二维码
* @param content 二维码里面的内容
*/
public static BufferedImage createImages(String content) throws Exception {
Hashtable hints = new Hashtable();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, 192, 192, hints);
int width = bitMatrix.getWidth();
int height = bitMatrix.getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
}
}
return image;
}
经过本人亲测,妥妥的
转载:https://blog.csdn.net/wzp12321/article/details/102467216
查看评论