本文實例為大家分享了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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
|
import java.awt.AlphaComposite; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public class NewImageUtils { /** * * @Title: 構造圖片 * @Description: 生成水印并返回java.awt.image.BufferedImage * @param file * 源文件(圖片) * @param waterFile * 水印文件(圖片) * @param x * 距離右下角的X偏移量 * @param y * 距離右下角的Y偏移量 * @param alpha * 透明度, 選擇值從0.0~1.0: 完全透明~完全不透明 * @return BufferedImage * @throws IOException */ public static BufferedImage watermark(File file, File waterFile, int x, int y, float alpha) throws IOException { // 獲取底圖 BufferedImage buffImg = ImageIO.read(file); // 獲取層圖 BufferedImage waterImg = ImageIO.read(waterFile); // 創建Graphics2D對象,用在底圖對象上繪圖 Graphics2D g2d = buffImg.createGraphics(); int waterImgWidth = waterImg.getWidth(); // 獲取層圖的寬度 int waterImgHeight = waterImg.getHeight(); // 獲取層圖的高度 // 在圖形和圖像中實現混合和透明效果 g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha)); // 繪制 g2d.drawImage(waterImg, x, y, waterImgWidth, waterImgHeight, null ); g2d.dispose(); // 釋放圖形上下文使用的系統資源 return buffImg; } /** * 輸出水印圖片 * * @param buffImg * 圖像加水印之后的BufferedImage對象 * @param savePath * 圖像加水印之后的保存路徑 */ private void generateWaterFile(BufferedImage buffImg, String savePath) { int temp = savePath.lastIndexOf( "." ) + 1 ; try { ImageIO.write(buffImg, savePath.substring(temp), new File(savePath)); } catch (IOException e1) { e1.printStackTrace(); } } /** * * @param args * @throws IOException * IO異常直接拋出了 * @author bls */ public static void main(String[] args) throws IOException { String sourceFilePath = "D://img//di.png" ; String waterFilePath = "D://img//ceng.png" ; String saveFilePath = "D://img//new.png" ; NewImageUtils newImageUtils = new NewImageUtils(); // 構建疊加層 BufferedImage buffImg = NewImageUtils.watermark( new File(sourceFilePath), new File(waterFilePath), 0 , 0 , 1 .0f); // 輸出水印圖片 newImageUtils.generateWaterFile(buffImg, saveFilePath); } } |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://www.cnblogs.com/bilaisheng/p/5500223.html