Wednesday, July 27, 2011

How to detect transparent pixel in java and how change transparent pixels

In images we represent each pixel represent by 32 bits.Bit assignment is doing as follows. Normally in Buffered images if we used type TYPE_INT_ARGB we do this way.See the image shown below.

 

So you can see if we need to detect alpha part we have to consider bits 31 to 24 so we need to shift right side by 24 bits then color related bits will go out. Then we will have only Alpha bits at location 7 to 0 then we will do and operation with 0xFF (that means 11111111) so we will get only 0 to 7 bits.
Same way you can use to detect red ,blue and green components by shifting 0,8,16.

Next we will see how we can do this by programme using java language.Here below you can see how to load gif transparent image and how to store it after modification to transparent pixels.
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;

public class test {
    public static void main() {
        // Get Image
        ImageIcon icon = new ImageIcon("/home/sanjeewa/Desktop/xparent.gif");
        Image image = icon.getImage();
        // Create empty BufferedImage, sized to Image
        BufferedImage buffImage =
                new BufferedImage(
                        image.getWidth(null),
                        image.getHeight(null),
                        BufferedImage.TYPE_INT_ARGB);
        Graphics g = buffImage.createGraphics();
        g.drawImage(image, 0, 0, null);
        //Dispose the Graphics
        g.dispose();
        //Here 2 for loops used for iterate through each and every pixel in image
        for (int i = 0; i < buffImage.getWidth(); i++) {
            for (int j = 0; j < buffImage.getHeight(); j++) {
                //signed bit shift right
                /*
                How to extract different color components
                blue = pix & 0xFF;
                green = (pix>>8) & 0xFF;
                red = (pix>>16) & 0xFF;
                alpha = (pix>>24) & 0xFF;
                 */
                int alpha = (buffImage.getRGB(i, j) >> 24) & 0xff;
                if (alpha == 0) {
                   //Now we will have pixel with Alpha 0 (Transparent pixel)
                   //As example If you need to fill transparent pixels with white color
                   //use this code 
                   //buffImage.setRGB(i, j, Color.white.getRGB());
                   buffImage.setRGB(i, j, 0);
                } else {

                }
            }
        }
        try {
             //Write back modified file to file system
            String file_name = "/home/sanjeewa/Desktop/sss.png";
            File file = new File(file_name);
            ImageIO.write(buffImage, "png", file);
        } catch (Exception e) {
        }
    }
}