How to convert an image into a transparent image in java

前端 未结 3 1920
花落未央
花落未央 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:39

    This method will make background transparent. You need to pass the image you want to modify, colour, and tolerance.

    final int color = ret.getRGB(0, 0);
    final Image imageWithTransparency = makeColorTransparent(ret, new Color(color), 10);
    final BufferedImage transparentImage = imageToBufferedImage(imageWithTransparency);
    
    private static BufferedImage imageToBufferedImage(final Image image) {
            final BufferedImage bufferedImage =
                new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
            final Graphics2D g2 = bufferedImage.createGraphics();
            g2.drawImage(image, 0, 0, null);
            g2.dispose();
            return bufferedImage;
    }
    
    
    private static Image makeColorTransparent(final BufferedImage im, final Color color, int tolerance) {
        int temp = 0;
    
        if (tolerance < 0 || tolerance > 100) {
    
            System.err.println("The tolerance is a percentage, so the value has to be between 0 and 100.");
    
            temp = 0;
    
        } else {
    
            temp = tolerance * (0xFF000000 | 0xFF000000) / 100;
    
        }
    
        final int toleranceRGB = Math.abs(temp);
    
    
    
        final ImageFilter filter = new RGBImageFilter() {
    
            // The color we are looking for (white)... Alpha bits are set to opaque
    
            public int markerRGBFrom = (color.getRGB() | 0xFF000000) - toleranceRGB;
    
            public int markerRGBTo = (color.getRGB() | 0xFF000000) + toleranceRGB;
    
    
    
            public final int filterRGB(final int x, final int y, final int rgb) {
    
                if ((rgb | 0xFF000000) >= markerRGBFrom && (rgb | 0xFF000000) <= markerRGBTo) {
    
                    // Mark the alpha bits as zero - transparent
    
                    return 0x00FFFFFF & rgb;
    
                } else {
    
                    // Nothing to do
    
                    return rgb;
    
                }
    
            }
    
        }; 
    
        final ImageProducer ip = new FilteredImageSource(im.getSource(), filter);
    
        return Toolkit.getDefaultToolkit().createImage(ip);
    }
    

提交回复
热议问题