java對圖片進行透明化處理


 1 package utils;
 2 
 3 import java.awt.Graphics2D;
 4 import java.awt.image.BufferedImage;
 5 import java.io.File;
 6 
 7 import javax.imageio.ImageIO;
 8 import javax.swing.ImageIcon;
 9 
10 public class TestMainPNG{
11     
12     public static void main(String[] args) throws Exception{
13         BufferedImage image = ImageIO.read(new File("C:/Users/grand/Desktop/lanzhou.jpg"));
14         // 高度和寬度
15         int height = image.getHeight();
16         int width = image.getWidth();
17         
18         // 生產背景透明和內容透明的圖片
19         ImageIcon imageIcon = new ImageIcon(image);
20         BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
21         Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics(); // 獲取畫筆
22         g2D.drawImage(imageIcon.getImage(), 0, 0, null); // 繪制Image的圖片,使用了imageIcon.getImage(),目的就是得到image,直接使用image就可以的
23 
24         int alpha = 0; // 圖片透明度
25         // 外層遍歷是Y軸的像素
26         for (int y = bufferedImage.getMinY(); y < bufferedImage.getHeight(); y++) {
27             // 內層遍歷是X軸的像素
28             for (int x = bufferedImage.getMinX(); x < bufferedImage.getWidth(); x++) {
29                 int rgb = bufferedImage.getRGB(x, y);
30                 // 對當前顏色判斷是否在指定區間內
31                 if (colorInRange(rgb)){
32                     alpha = 0;
33                 }else{
34                     // 設置為不透明
35                     alpha = 255;
36                 }
37                 // #AARRGGBB 最前兩位為透明度
38                 rgb = (alpha << 24) | (rgb & 0x00ffffff);
39                 bufferedImage.setRGB(x, y, rgb);
40             }
41         }
42         // 繪制設置了RGB的新圖片,這一步感覺不用也可以只是透明地方的深淺有變化而已,就像蒙了兩層的感覺
43         g2D.drawImage(bufferedImage, 0, 0, null);
44 
45         // 生成圖片為PNG
46         ImageIO.write(bufferedImage, "png", new File("C:/Users/grand/Desktop/lanzhou.png"));
47         MyLogger.logger.info("完成畫圖");
48     }
49     
50     // 判斷是背景還是內容
51     public static boolean colorInRange(int color) {
52         int red = (color & 0xff0000) >> 16;// 獲取color(RGB)中R位
53         int green = (color & 0x00ff00) >> 8;// 獲取color(RGB)中G位
54         int blue = (color & 0x0000ff);// 獲取color(RGB)中B位
55         // 通過RGB三分量來判斷當前顏色是否在指定的顏色區間內
56         if (red >= color_range && green >= color_range && blue >= color_range){
57             return true;
58         };
59         return false;
60     }
61     
62     //色差范圍0~255
63     public static int color_range = 210;
64     
65 }

 

說明:左邊圖片是白色的底,右邊圖片是透明的底。

個人感覺:使用畫筆操作的是畫中的內容,透明化是對畫布的操作而不是內容的操作。

 

 

 

 


免責聲明!

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



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