添加水印图片方法
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
public static void markImageByIcon(String iconPath, String srcImgPath, String targerPath, Integer location, Integer degree) {
OutputStream os = null;
try {
Image srcImg = ImageIO.read(new File(srcImgPath));
int width = srcImg.getWidth(null);
int height = srcImg.getHeight(null);
BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = buffImg.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(srcImg, 0, 0, width, height, null);
if (null != degree) {
g.rotate(Math.toRadians(degree), (double) buffImg.getWidth() / 2, (double) buffImg.getHeight() / 2);
}
ImageIcon imgIcon = new ImageIcon(iconPath);
Image syImg = imgIcon.getImage();
float alpha = 0.5f;
int syWidth = syImg.getWidth(null);
int syHeight = syImg.getHeight(null);
int newSyWidth = syWidth;
int newSyHeight = syHeight;
if (syWidth > width) {
newSyWidth = width;
newSyHeight = (int) ((double)newSyWidth / syWidth * height);
}
if (newSyHeight > height) {
newSyHeight = height;
newSyWidth = (int) ((double)newSyHeight / syHeight * newSyWidth);
}
int x = 0, y = 0;
switch (location) {
case 1: break;
case 2:
x = width - newSyWidth;
break;
case 3:
y = height - newSyHeight;
break;
case 4:
x = width - newSyWidth;
y = height - newSyHeight;
break;
case 5:
x = (width - newSyWidth) / 2;
y = (height - newSyHeight) / 2;
break;
default: break;
}
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
g.drawImage(syImg, x, y, newSyWidth, newSyHeight, null);
g.dispose();
os = new FileOutputStream(targerPath);
ImageIO.write(buffImg, "JPG", os);
log.info("图片完成添加Icon印章... srcImgPath:{}, targerPath:{}", srcImgPath, targerPath);
} catch (Exception e) {
log.info("图片添加Icon印章异常! iconPath:{}, srcImgPath:{}, targerPath:{}, location:{}", iconPath, srcImgPath, targerPath, location);
} finally {
try {
if (null != os) {
os.close();
}
} catch (Exception e) {
log.error("", e);
}
}
}
重载
public static void markImageByIcon(String iconPath, String srcImgPath, String targerPath) {
markImageByIcon(iconPath, srcImgPath, targerPath, 5, null);
}