Wednesday, April 8, 2009

Convert Colored Images to Black And white in java


Sometime you want to convert colored images to black and white.
Here i am giving you the simple method to do so.
Just see below.

//example for coverting colored image to black and white
import java.awt.image.*;
import javax.imageio.ImageIO;
import java.awt.*;

class BlackAndWhite
          public static void main(String asr[])
                             //colored image path
                             BufferedImage image =  

                             //getting width and height of image
                             double image_width = image.getWidth();
                             double image_height = image.getHeight();

                             BufferedImage bimg = null;
                             BufferedImage img = image;

                             //drawing a new image      
                             bimg = new BufferedImage((int)image_width, (int)image_height,
                             Graphics2D gg = bimg.createGraphics();
                             gg.drawImage(img, 0, 0, img.getWidth(null), img.getHeight(null), null);

                             //saving black and white image onto drive
                             String temp = "blackAndwhite.jpeg";
                             File fi = new File("D:\\My Program\\" + temp);
                             ImageIO.write(bimg, "jpg", fi);
                   catch (Exception e)