C:\ece595_06\image>java gray2 Elapsed time 68.5105 milliseconds 327 x 215 Area 0.0703050 megapixels Time per megapixel 974.476 milliseconds
gray2.java
import java.awt.*; import java.awt.image.*; import java.awt.color.*; import java.io.*; import javax.imageio.*; import javax.swing.*; public class gray2 { public static void main(String [] args) { String filename = "bld.jpg"; if (args.length>0) filename = args[0]; showImage f1 = new showImage(filename); f1.setLocation(100,100); f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); int w = f1.getWidth(); int h = f1.getHeight(); long start = System.nanoTime(); BufferedImage grayImage = rgb2gray(f1.img); long etime = System.nanoTime() - start; double elapsed_time = 1e-6*(double)etime; System.out.format("Elapsed time %g milliseconds%n",elapsed_time); double area = f1.img.getWidth()*f1.img.getHeight()*1e-6; System.out.format("%d x %d Area %g megapixels%n",f1.img.getWidth(), f1.img.getHeight(), area); System.out.format("Time per megapixel %g milliseconds%n",elapsed_time/area); showImage f2 = new showImage(grayImage,"gray version"); f2.setLocation(120+w,100); f2.writeImage("gray","png"); } public static BufferedImage rgb2gray(BufferedImage img) { int w1 = img.getWidth(); int h1 = img.getHeight(); // int value[][] = new int[w1][h1]; int type = BufferedImage.TYPE_INT_RGB; BufferedImage gray = new BufferedImage(w1, h1, type);// new image int value, v, r, g, b; for (int i = 0; i < w1; i++) { for (int j = 0; j < h1; j++) { value = img.getRGB(i, j); // read and store pixel value r = (value >> 16) & 0xFF; g = (value >> 8) & 0xFF; b = value & 0xFF; v = (r + g + b) / 3; // grey by averaging the pixels value = 0xFF000000 + (v << 16) + (v << 8) + v; gray.setRGB(i, j, value); } } return gray; } public static int create_rgb(int alpha, int r, int g, int b) { int rgb = (alpha << 24) + (r << 16) + (g << 8) + b; return rgb; } public static int get_alpha(int rgb) { return (rgb >> 24) & 0xFF; // return rgb & 0xFF000000; } public static int get_red(int rgb) { return (rgb >> 16) & 0xFF; // return rgb & 0x00FF0000; } public static int get_green(int rgb) { return (rgb >> 8) & 0xFF; } public static int get_blue(int rgb) { return rgb & 0xFF; } }
Maintained by John Loomis, updated Thu Oct 10 12:05:56 2013