How to convert an image into a transparent image in java

前端 未结 3 1915
花落未央
花落未央 2021-01-07 01:53

How to convert a white background of an image into a transparent background? Can anyone tel me how to do this?

3条回答
  •  甜味超标
    2021-01-07 02:29

    Here is my solution. This filter will remove the background from any image as long as the background image color is in the top left corner.

    private static class BackgroundFilter extends RGBImageFilter{
    
        boolean setUp = false;
        int bgColor;
    
        @Override
        public int filterRGB(int x, int y, int rgb) {
            int colorWOAlpha = rgb & 0xFFFFFF;
            if( ! setUp && x == 0 && y == 0 ){
                bgColor = colorWOAlpha;
                setUp = true;
            }
            else if( colorWOAlpha == bgColor )
                return colorWOAlpha;
            return rgb;
        }
    }
    

    Elsewhere...

    ImageFilter bgFilter = new BackgroundFilter();
    ImageProducer ip = new FilteredImageSource(image.getSource(), bgFilter);
    image = Toolkit.getDefaultToolkit().createImage(ip);
    

提交回复
热议问题