Grayscale.java


Below is the syntax highlighted version of Grayscale.java from §3.1 Using Data Types.

/*************************************************************************
 *  Compilation:  javac Grayscale.java
 *  Execution:    java Grayscale filename
 * 
 *  Reads in an image from a file, and flips it horizontally.
 *
 *  % java Grayscale image.jpg
 *
 *************************************************************************/

import java.awt.Color;

public class Grayscale {

    public static void main(String args[]) {
        Picture pic = new Picture(args[0]);
        int width  = pic.width();
        int height = pic.height();


        pic.show();

        // convert to grayscale
        for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
                Color c = pic.getColor(i, j);
                int r = c.getRed();
                int g = c.getGreen();
                int b = c.getBlue();
                int gray = (int) (0.2989*r + 0.5870*g + 0.1140*b);  // NTSC formula
                c = new Color(gray, gray, gray);
                pic.setColor(i, j, c);
            }
        }

        pic.show();
    }
 

   
}


Last updated: Mon Oct 4 12:33:08 EDT 2004 .
Copyright © 2004, Robert Sedgewick and Kevin Wayne.