/** * Encapsulation for easy picture reading. * CIS 120 HW4: Simple Machine Learning * @author Kuzman Ganchev (2006) */ import java.awt.BorderLayout; import java.awt.Color; import java.awt.Graphics; import java.awt.Image; import java.awt.image.BufferedImage; import java.awt.image.WritableRaster; import java.io.File; import java.io.FileNotFoundException; import javax.imageio.*; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class SimplePicture { /** the image in a format easy for displaying */ protected BufferedImage bufferedImage; /** a raster for the image */ protected WritableRaster raster; /** the name of the file used to create the SimplePicture */ private String name; /** creates a new SimplePicture object of the specified type by reading in * the given file. * @param filename the location of the image file to read */ SimplePicture(String filename) throws FileNotFoundException, NotAPictureException { load(filename); name=filename; } /** get the width of the image */ public int getWidth() { return bufferedImage.getWidth(); } /** get the height of the image */ public int getHeight() { return bufferedImage.getHeight(); } /** get the name used to create this picture */ public String getName() { return name;} /** load the image from the specified image into this Picture object * @param filename the location of the file * @throws FileNotFoundException if the file does not exist * @throws NotAPictureException if the file exists but we could not * load it.*/ public void load(String filename) throws FileNotFoundException, NotAPictureException { ImageIcon icon; if ((new File(filename)).exists()) icon = new ImageIcon(filename); else throw new FileNotFoundException(filename); Image image = icon.getImage(); if (image.getHeight(null)<0 || image.getWidth(null)<0){ throw new NotAPictureException(); } bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_BYTE_GRAY); Graphics g = bufferedImage.getGraphics(); g.drawImage(image, 0, 0, null); g.dispose(); raster = bufferedImage.getRaster(); } /** get the greyscale value for this picture at the specified * location. The value is in the range 0-255. * @param x the x-coordinate * @param y the y-coordinate */ public int getValue(int x, int y){ int val = 0; int[] pix = raster.getPixel(x, y, (int [])null); for (int i=0; i