給圖片加二維碼啥的如今都是屢見不鮮的,常常會用到的,是吧
@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;
}複製代碼