JAVA實現圖片疊加效果


 1 import java.awt.AlphaComposite;
 2 import java.awt.Graphics2D;
 3 import java.awt.image.BufferedImage;
 4 import java.io.File;
 5 import java.io.IOException;
 6 
 7 import javax.imageio.ImageIO;
 8 public class NewImageUtils {
 9     /**
10      * 
11      * @Title: 構造圖片
12      * @Description: 生成水印並返回java.awt.image.BufferedImage
13      * @param file
14      *            源文件(圖片)
15      * @param waterFile
16      *            水印文件(圖片)
17      * @param x
18      *            距離右下角的X偏移量
19      * @param y
20      *            距離右下角的Y偏移量
21      * @param alpha
22      *            透明度, 選擇值從0.0~1.0: 完全透明~完全不透明
23      * @return BufferedImage
24      * @throws IOException
25      */
26     public static BufferedImage watermark(File file, File waterFile, int x, int y, float alpha) throws IOException {
27         // 獲取底圖
28         BufferedImage buffImg = ImageIO.read(file);
29         // 獲取層圖
30         BufferedImage waterImg = ImageIO.read(waterFile);
31         // 創建Graphics2D對象,用在底圖對象上繪圖
32         Graphics2D g2d = buffImg.createGraphics();
33         int waterImgWidth = waterImg.getWidth();// 獲取層圖的寬度
34         int waterImgHeight = waterImg.getHeight();// 獲取層圖的高度
35         // 在圖形和圖像中實現混合和透明效果
36         g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
37         // 繪制
38         g2d.drawImage(waterImg, x, y, waterImgWidth, waterImgHeight, null);
39         g2d.dispose();// 釋放圖形上下文使用的系統資源
40         return buffImg;
41     }
42 
43     /**
44      * 輸出水印圖片
45      * 
46      * @param buffImg
47      *            圖像加水印之后的BufferedImage對象
48      * @param savePath
49      *            圖像加水印之后的保存路徑
50      */
51     private void generateWaterFile(BufferedImage buffImg, String savePath) {
52         int temp = savePath.lastIndexOf(".") + 1;
53         try {
54             ImageIO.write(buffImg, savePath.substring(temp), new File(savePath));
55         } catch (IOException e1) {
56             e1.printStackTrace();
57         }
58     }
59 
60     /**
61      * 
62      * @param args
63      * @throws IOException
64      *             IO異常直接拋出了
65      * @author bls
66      */
67     public static void main(String[] args) throws IOException {
68         String sourceFilePath = "D://img//di.png";
69         String waterFilePath = "D://img//ceng.png";
70         String saveFilePath = "D://img//new.png";
71         NewImageUtils newImageUtils = new NewImageUtils();
72         // 構建疊加層
73         BufferedImage buffImg = NewImageUtils.watermark(new File(sourceFilePath), new File(waterFilePath), 0, 0, 1.0f);
74         // 輸出水印圖片
75         newImageUtils.generateWaterFile(buffImg, saveFilePath);
76     }
77 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM