Java picture background color becomes transparent

Java image background color becomes transparent

  • illustrate
  • Effect
    • Before processing
    • After processing

Description

Without further ado, let’s go directly to the tool class, which provides methods
noBackground() determines whether the background color of the image is transparent.
imageToPng() makes the background color of the image transparent.

Effect

Before processing

After processing

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
import java.io.*;

public class ImageTest {<!-- -->
    public static void main(String[] args) throws Exception{<!-- -->
        String inFilePath = "",outFilePath = "";
        inFilePath = "D:\tmp\images\110.png";
        outFilePath = "D:\tmp\images\1104.png";
        bufferWrite(imageToPng(new File(inFilePath)),outFilePath);
        System.out.println("ok");
    }

    /**
     * Set transparent background color for pictures
     * @param imageBytes original image
     * */
    public static byte[] imageToPng(byte [] imageBytes)throws Exception{<!-- -->
        ByteArrayInputStream bais = null;
        try{<!-- -->
            bais = new ByteArrayInputStream(imageBytes);
            return imageToPng(bais);
        }finally {<!-- -->
            FileUtil.closeStream(bais);
        }
    }

    /**
     * Set transparent background color for pictures
     * @param file original image
     * */
    public static byte[] imageToPng(File file)throws Exception{<!-- -->
        BufferedImage bufferedImage = ImageIO.read(file);
        return imageToPng(bufferedImage);
    }

    /**
     * Set transparent background color for pictures
     * @param is original image
     * */
    public static byte[] imageToPng(InputStream is)throws Exception{<!-- -->
        BufferedImage bufferedImage = ImageIO.read(is);
        return imageToPng(bufferedImage);
    }

    /**
     * Set transparent background color for pictures
     * @param image original image
     * */
    public static byte[] imageToPng(BufferedImage image)throws Exception{<!-- -->

        if(image==null)
            return null;
        ByteArrayOutputStream baos = null;
        byte [] bytes = null;

        if(noBackground(image)){<!-- -->
            /*When the background is transparent, return directly to the original image*/
            baos = new ByteArrayOutputStream();
            ImageIO.write(image, "png", baos);
            bytes = baos.toByteArray();
            return bytes;
        }

        try {<!-- -->
            baos = new ByteArrayOutputStream();

            // height and width
            int height = image.getHeight();
            int width = image.getWidth();

            // Initialize pictures with transparent background and transparent content
            ImageIcon imageIcon = new ImageIcon(image);
            BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
            Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics(); // Get the brush
            // Draw the picture of Image
            g2D.drawImage(imageIcon.getImage(), 0, 0, null);

            int alpha = 0; // Image transparency
            // The outer traversal is the pixels of the Y axis
            for (int y = bufferedImage.getMinY(); y < bufferedImage.getHeight(); y + + ) {<!-- -->
                //The inner traversal is the pixels on the X axis
                for (int x = bufferedImage.getMinX(); x < bufferedImage.getWidth(); x + + ) {<!-- -->
                    int rgb = bufferedImage.getRGB(x, y);
                    // Determine whether the current color is within the specified range
                    if (colorInRange(rgb)){<!-- -->
                        alpha = 0;
                    }else{<!-- -->
                        // Set to opaque
                        alpha = 255;
                    }
                    //The first two digits are transparency
                    rgb = (alpha << 24) | (rgb & amp; 0x00ffffff);
                    bufferedImage.setRGB(x, y, rgb);
                }
            }
            //Draw a new picture with RGB settings. You don’t need to use this step. It’s just that the depth of the transparent area changes. It feels like there are two layers.
            g2D.drawImage(bufferedImage, 0, 0, null);

            // Generate image as PNG
            ImageIO.write(bufferedImage, "png", baos);
            bytes = baos.toByteArray();
        }finally {<!-- -->
            FileUtil.closeStream(baos);
        }
        return bytes;
    }

    //Color difference range 0~255
    public static int color_range = 210;
    // Determine whether it is background or content
    public static boolean colorInRange(int color) {<!-- -->
        int red = (color & amp; 0xff0000) >> 16; // Get the R bit in color (RGB)
        int green = (color & amp; 0x00ff00) >> 8; // Get the G bit in color (RGB)
        int blue = (color & amp; 0x0000ff); // Get the B bit in color (RGB)
        // Use RGB three components to determine whether the current color is within the specified color range
        if (red >= color_range & amp; & amp; green >= color_range & amp; & amp; blue >= color_range){<!-- -->
            return true;
        };
        return false;
    }

    /**
     * Determine whether there is a background color
     * @return
     * true without background color; false with background color
     * */
    public static boolean noBackground(byte [] imageBytes)throws Exception{<!-- -->
        ByteArrayInputStream bais = null;
        try{<!-- -->
            bais = new ByteArrayInputStream(imageBytes);
            return noBackground(bais);
        }finally {<!-- -->
            FileUtil.closeStream(bais);
        }
    }

    /**
     * Determine whether there is a background color
     * @return
     * true without background color; false with background color
     * */
    public static boolean noBackground(InputStream is)throws Exception{<!-- -->
        BufferedImage bufferedImage = ImageIO.read(is);
        return noBackground(bufferedImage);
    }

    /**
     * Determine whether there is a background color
     * @return
     * true without background color; false with background color
     * */
    public static boolean noBackground(BufferedImage bufferedImage)throws Exception{<!-- -->
        if(bufferedImage ==null)
            return false;
        int height = bufferedImage.getHeight();
        int width = bufferedImage.getWidth();

        for(int w=0;w<width;w + + ){<!-- -->
            for(int h=0;h<height;h + + ){<!-- -->
                int rgb = bufferedImage.getRGB(w,h);
                if(rgb >> 24==0){<!-- -->
                    return true;
                }
            }
        }
        return false;
    }
    public static void bufferWrite(byte[] data,String filePath) throws Exception {<!-- -->
        FileOutputStream fos = null;
        try{<!-- -->
            fos = new FileOutputStream(filePath);
            fos.write(data);
        }finally{<!-- -->
            if(fos!=null)
                fos.close();
        }
    }
}