Converting Images from rgb to grayscale with Java
Not sure what motivated me here but I took a little time and came up with this. It takes the original image file ( can be a multitude of formats, has worked with both jpg and png so far) and outputs a grayscale image (jpeg or png).
Here is the code… (hint
import javax.imageio.*;
import javax.imageio.*;
import java.io.*;
import java.awt.image.*;
public class GreyScale {
public static void main(String [] pie) {
// Argument Checks
if(!((pie.length == 3) && (new File(pie[0]).exists()) && (pie[2].equals("jpeg") || pie[2].equals("png"
System.out.println("Usage: java GreyScale {original image} {modified image} {Output Format}\nO
System.exit(0);
}
BufferedImage image = null;
try {
image = ImageIO.read(new File(pie[0])); // Read in the original file
} catch(IOException e) {
System.err.println("Error reading in file, check file name and format");
System.exit(0);
}
// loop through every pixel in the image
for(int x = 0; x <image.getWidth(); x ++) {
for(int y = 0; y < image.getHeight(); y++) {
int RGB = image.getRGB(x,y); // Get the rgb of the pixel
int blue = (RGB & 0x000000FF);
int green = (RGB & 0x0000FF00) >> 8;
int red = (RGB & 0x00FF0000) >> 16;
int average = (int) ((.11 * blue) + (.59 * green) + (.3 * red));
int newRGB = 0xFF000000 + (average << 16) + (average << 8) + average; // and reassign
image.setRGB(x,y,newRGB);
}
}
try {
ImageIO.write(image, pie[2], new File(pie[1])); // Writes the new greyscale file.
} catch(IOException e) {
System.err.println("Unable to output results");
}
}
}
UPDATE: Edited thanks to the comment from Gasper. Swapped out the Color class for bitwise operations and it seems to be working well. Also figured out how to format the code in a way that looks better.
UPDATE: Updated to use a different algorithm for finding the grey intensity. Instead of averaging used values based on human vision. (30% red, 59% Green, 11% Red) Taken from Wikipedia.













July 13th, 2009 at 6:55 am
Yey, I wrote quite similar code some time ago when I was writing simple ocr.
If I understood you with ‘I need to take the time to actually learn what the single int version does.’ you had in mind strange values that getRGB() returns.
If so, RGB => alpha – red – green – blue.
0xFF000000 = black
0xFF0000FF = blue
–just found your blog. It’s quit difficult to read the code
have a nice day
July 13th, 2009 at 1:13 pm
Thanks for the info, I’m going to try to find a way to add some white space. It stripped all the tabs out when I pasted it.