그림 투명 화 (순 전 히 전재)

2331 단어 Java
package utils;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

public class TestMainPNG{
    
    public static void main(String[] args) throws Exception{
        BufferedImage image = ImageIO.read(new File("C:/Users/grand/Desktop/lanzhou.jpg"));
        //      
        int height = image.getHeight();
        int width = image.getWidth();
        
        //               
        ImageIcon imageIcon = new ImageIcon(image);
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
        Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics(); //     
        g2D.drawImage(imageIcon.getImage(), 0, 0, null); //   Image   

        int alpha = 0; //      
        //      Y    
        for (int y = bufferedImage.getMinY(); y < bufferedImage.getHeight(); y++) {
            //      X    
            for (int x = bufferedImage.getMinX(); x < bufferedImage.getWidth(); x++) {
                int rgb = bufferedImage.getRGB(x, y);
                //                
                if (colorInRange(rgb)){
                    alpha = 0;
                }else{
                    //       
                    alpha = 255;
                }
                // #AARRGGBB         
                rgb = (alpha << 24) | (rgb & 0x00ffffff);
                bufferedImage.setRGB(x, y, rgb);
            }
        }
        //      RGB    
        g2D.drawImage(bufferedImage, 0, 0, null);

        //      PNG
        ImageIO.write(bufferedImage, "png", new File("C:/Users/grand/Desktop/lanzhou.png"));
        MyLogger.logger.info("    ");
    }
    
    //          
    public static boolean colorInRange(int color) {
        int red = (color & 0xff0000) >> 16;//   color(RGB) R 
        int green = (color & 0x00ff00) >> 8;//   color(RGB) G 
        int blue = (color & 0x0000ff);//   color(RGB) B 
        //   RGB                     
        if (red >= color_range && green >= color_range && blue >= color_range){
            return true;
        };
        return false;
    }
    
    //    0~255
    public static int color_range = 210;
    
}

좋은 웹페이지 즐겨찾기