import java.awt.Color; import java.io.File; import java.io.IOException; import javax.swing.JFileChooser; import princeton.Picture; /** * Example program to show how the Picture class works and to show how to * iterate over all the pixels in an image to alter them. *

* * @author ola * @date August 7, 2009 * */ public class ClearBitsFromImage { protected static JFileChooser ourOpenChooser = new JFileChooser(System .getProperties().getProperty("user.dir")); public static final int BITS_TO_CLEAR = 4; /** * Return a new color based on parameter, but in which low-order bits are * cleared. Number of bits cleared is specified by constant BITS_TO_CLEAR; * * @param c * is the color on which returned value is based * @return a color whose RGB components are based on those of parameter c, * but with low-order BITS_TO_CLEAR bits cleared/zeroed in each RGB * component. */ public Color reduce(Color c) { int r = c.getRed(); int g = c.getGreen(); int b = c.getBlue(); int factor = (int) Math.pow(2, BITS_TO_CLEAR); r = (r / factor) * factor; g = (g / factor) * factor; b = (b / factor) * factor; return new Color(r, g, b); } /** * Return a new picture based on parameter target but in which each pixel * has had low-order bits cleared * * @param target * is the image that's the basis for the new image * @return an image based on target, but in which low-order BITS_TO_CLEAR * bits are cleared. */ public Picture clear(Picture target) { int width = target.width(); int height = target.height(); target.show(); Picture pic = new Picture(width, height); for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { Color sc = target.get(i, j); Color cc = reduce(sc); pic.set(i, j, cc); } } return pic; } public static void main(String[] args) throws IOException { String fname = null; ourOpenChooser .setDialogTitle("Choose target image to reduce in quality"); int action = ourOpenChooser.showOpenDialog(null); if (action == JFileChooser.APPROVE_OPTION) { File f = ourOpenChooser.getSelectedFile(); fname = f.getCanonicalPath(); Picture source = new Picture(fname); source.show(); ClearBitsFromImage strip = new ClearBitsFromImage(); Picture reduced = strip.clear(source); reduced.show(); } } }