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 }

说明:左边图片是白色的底,右边图片是透明的底。

个人感觉:使用画笔操作的是画中的内容,透明化是对画布的操作而不是内容的操作。

 

原文地址:https://www.cnblogs.com/TheoryDance/p/7094376.html