java实现一张透明背景的图片,添加图片水印

java实现一张透明背景的图片,添加图片水印

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
public static void createWaterMarkByIcon(File srcImageFile, File logoImageFile,
File outputImageFile, double degree) {

OutputStream os = null;
try {
Image srcImg = ImageIO.read(srcImageFile);

BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null),
srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);

Graphics2D graphics = buffImg.createGraphics();

buffImg = graphics.getDeviceConfiguration().createCompatibleImage(srcImg.getWidth(null), srcImg.getWidth(null), Transparency.TRANSLUCENT);
graphics = buffImg.createGraphics();
// graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);

int imgWidth = srcImg.getWidth(null);
int imgHeight = srcImg.getHeight(null);

graphics.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null),
srcImg.getHeight(null), Image.SCALE_SMOOTH), 0, 0, null);

ImageIcon logoImgIcon = new ImageIcon(ImageIO.read(logoImageFile));
Image logoImg = logoImgIcon.getImage();

//旋转
if (degree>0) {
graphics.rotate(Math.toRadians(degree),
(double) buffImg.getWidth() / 2,
(double) buffImg.getWidth() / 2);
}

float alpha = 0.7f; // 透明度
graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));

//水印 的位置
int logoWidth = imgWidth/4;
int logoHeight = logoWidth*17/20;

graphics.drawImage(logoImg, buffImg.getWidth()-logoWidth, buffImg.getHeight()-logoHeight,logoWidth,logoHeight, null);
// graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
graphics.dispose();

os = new FileOutputStream(outputImageFile);
// 生成图片
ImageIO.write(buffImg, "PNG", os);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != os)
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

水印位置根据自己实际情况调整。
参考文档:
https://blog.csdn.net/gingerredjade/article/details/53193014

实现list的深拷贝
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×