Sunday, November 23, 2014

Java: Color Image To Grayscale

Share it Please

The following source code is an illustration of how to convert a color image to grayscale (black & white). This example shows usage of IO for images, file operations and RGB colors in java.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package imageColor;

import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class test {
 public static void main(String[] args){
  BufferedImage image = null;
  try{
   image = ImageIO.read(new File("File Location"));
  } catch(Exception e){
   System.out.println(e);
  }
  
  convertToGrayscale(image);
  RenderedImage im = image;
  
  try{
   ImageIO.write(im, "jpg", new File("save location"));
  } catch (IOException e){
   System.out.println(e);
  }
  
 }
 private static void convertToGrayscale(final BufferedImage image){
     for(int i=0; i<image.getWidth(); i++){
         for(int j=0; j<image.getHeight(); j++){
             int color = image.getRGB(i,j);
  
             int alpha = (color >> 24) & 255;
             int red = (color >> 16) & 255;
             int green = (color >> 8) & 255;
             int blue = (color) & 255;
  
             final int lum = (int)(0.2126 * red + 0.7152 * green + 0.0722 * blue);
  
             alpha = (alpha << 24);
             red = (lum << 16);
             green = (lum << 8);
             blue = lum;
  
             color = alpha + red + green + blue;
  
             image.setRGB(i,j,color);
         }
     }
 }

}

No comments:

Post a Comment

Blogroll

About