calcpage

LACS08_Picture.java

Jun 20th, 2012
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 8.75 KB | None | 0 0
  1. /*************************************************************************
  2.  *  Compilation:  javac Picture.java
  3.  *  Execution:    java Picture imagename
  4.  *
  5.  *  Data type for manipulating individual pixels of an image. The original
  6.  *  image can be read from a file in jpg, gif, or png format, or the
  7.  *  user can create a blank image of a given size. Includes methods for
  8.  *  displaying the image in a window on the screen or saving to a file.
  9.  *
  10.  *  % java Picture mandrill.jpg
  11.  *
  12.  *  Remarks
  13.  *  -------
  14.  *   - pixel (x, y) is column x and row y, where (0, 0) is upper left
  15.  *
  16.  *   - see also GrayPicture.java for a grayscale version
  17.  *
  18.  *************************************************************************/
  19.  
  20. import java.awt.Color;
  21. import java.awt.FileDialog;
  22. import java.awt.Toolkit;
  23. import java.awt.event.ActionEvent;
  24. import java.awt.event.ActionListener;
  25. import java.awt.event.KeyEvent;
  26. import java.awt.image.BufferedImage;
  27. import java.io.File;
  28. import java.io.IOException;
  29. import java.net.URL;
  30. import javax.imageio.ImageIO;
  31. import javax.swing.ImageIcon;
  32. import javax.swing.JFrame;
  33. import javax.swing.JLabel;
  34. import javax.swing.JMenu;
  35. import javax.swing.JMenuBar;
  36. import javax.swing.JMenuItem;
  37. import javax.swing.KeyStroke;
  38.  
  39.  
  40. /**
  41.  *  This class provides methods for manipulating individual pixels of
  42.  *  an image. The original image can be read from a file in JPEG, GIF,
  43.  *  or PNG format, or the user can create a blank image of a given size.
  44.  *  This class includes methods for displaying the image in a window on
  45.  *  the screen or saving to a file.
  46.  *  <p>
  47.  *  By default, pixel (x, y) is column x, row y, where (0, 0) is upper left.
  48.  *  The method setOriginLowerLeft() change the origin to the lower left.
  49.  *  <p>
  50.  *  For additional documentation, see
  51.  *  <a href="http://introcs.cs.princeton.edu/31datatype">Section 3.1</a> of
  52.  *  <i>Introduction to Programming in Java: An Interdisciplinary Approach</i>
  53.  *  by Robert Sedgewick and Kevin Wayne.
  54.  */
  55. public final class Picture implements ActionListener {
  56.     private BufferedImage image;               // the rasterized image
  57.     private JFrame frame;                      // on-screen view
  58.     private String filename;                   // name of file
  59.     private boolean isOriginUpperLeft = true;  // location of origin
  60.     private int width, height;                 // width and height
  61.  
  62.    /**
  63.      * Create a blank w-by-h picture, where each pixel is black.
  64.      */
  65.     public Picture(int w, int h) {
  66.         width = w;
  67.         height = h;
  68.         image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
  69.         // set to TYPE_INT_ARGB to support transparency
  70.         filename = w + "-by-" + h;
  71.     }
  72.  
  73.    /**
  74.      * Create a picture by reading in a .png, .gif, or .jpg from
  75.      * the given filename or URL name.
  76.      */
  77.     public Picture(String filename) {
  78.         this.filename = filename;
  79.         try {
  80.             // try to read from file in working directory
  81.             File file = new File(filename);
  82.             if (file.isFile()) {
  83.                 image = ImageIO.read(file);
  84.             }
  85.  
  86.             // now try to read from file in same directory as this .class file
  87.             else {
  88.                 URL url = getClass().getResource(filename);
  89.                 if (url == null) { url = new URL(filename); }
  90.                 image = ImageIO.read(url);
  91.             }
  92.             width  = image.getWidth(null);
  93.             height = image.getHeight(null);
  94.         }
  95.         catch (IOException e) {
  96.             // e.printStackTrace();
  97.             throw new RuntimeException("Could not open file: " + filename);
  98.         }
  99.     }
  100.  
  101.    /**
  102.      * Create a picture by reading in a .png, .gif, or .jpg from a File.
  103.      */
  104.     public Picture(File file) {
  105.         try { image = ImageIO.read(file); }
  106.         catch (IOException e) {
  107.             e.printStackTrace();
  108.             throw new RuntimeException("Could not open file: " + file);
  109.         }
  110.         if (image == null) {
  111.             throw new RuntimeException("Invalid image file: " + file);
  112.         }
  113.     }
  114.  
  115.    /**
  116.      * Return a JLabel containing this Picture, for embedding in a JPanel,
  117.      * JFrame or other GUI widget.
  118.      */
  119.     public JLabel getJLabel() {
  120.         if (image == null) { return null; }         // no image available
  121.         ImageIcon icon = new ImageIcon(image);
  122.         return new JLabel(icon);
  123.     }
  124.  
  125.    /**
  126.      * Set the origin to be the upper left pixel.
  127.      */
  128.     public void setOriginUpperLeft() {
  129.         isOriginUpperLeft = true;
  130.     }
  131.  
  132.    /**
  133.      * Set the origin to be the lower left pixel.
  134.      */
  135.     public void setOriginLowerLeft() {
  136.         isOriginUpperLeft = false;
  137.     }
  138.  
  139.    /**
  140.      * Display the picture in a window on the screen.
  141.      */
  142.     public void show() {
  143.  
  144.         // create the GUI for viewing the image if needed
  145.         if (frame == null) {
  146.             frame = new JFrame();
  147.  
  148.             JMenuBar menuBar = new JMenuBar();
  149.             JMenu menu = new JMenu("File");
  150.             menuBar.add(menu);
  151.             JMenuItem menuItem1 = new JMenuItem(" Save...   ");
  152.             menuItem1.addActionListener(this);
  153.             menuItem1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
  154.                                      Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
  155.             menu.add(menuItem1);
  156.             frame.setJMenuBar(menuBar);
  157.  
  158.  
  159.  
  160.             frame.setContentPane(getJLabel());
  161.             // f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  162.             frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
  163.             frame.setTitle(filename);
  164.             frame.setResizable(false);
  165.             frame.pack();
  166.             frame.setVisible(true);
  167.         }
  168.  
  169.         // draw
  170.         frame.repaint();
  171.     }
  172.  
  173.    /**
  174.      * Return the height of the picture in pixels.
  175.      */
  176.     public int height() {
  177.         return height;
  178.     }
  179.  
  180.    /**
  181.      * Return the width of the picture in pixels.
  182.      */
  183.     public int width() {
  184.         return width;
  185.     }
  186.  
  187.    /**
  188.      * Return the color of pixel (i, j).
  189.      */
  190.     public Color get(int i, int j) {
  191.         if (isOriginUpperLeft) return new Color(image.getRGB(i, j));
  192.         else                   return new Color(image.getRGB(i, height - j - 1));
  193.     }
  194.  
  195.    /**
  196.      * Set the color of pixel (i, j) to c.
  197.      */
  198.     public void set(int i, int j, Color c) {
  199.         if (c == null) { throw new RuntimeException("can't set Color to null"); }
  200.         if (isOriginUpperLeft) image.setRGB(i, j, c.getRGB());
  201.         else                   image.setRGB(i, height - j - 1, c.getRGB());
  202.     }
  203.  
  204.    /**
  205.      * Is this Picture equal to obj?
  206.      */
  207.     public boolean equals(Object obj) {
  208.         if (obj == this) return true;
  209.         if (obj == null) return false;
  210.         if (obj.getClass() != this.getClass()) return false;
  211.         Picture that = (Picture) obj;
  212.         if (this.width()  != that.width())  return false;
  213.         if (this.height() != that.height()) return false;
  214.         for (int x = 0; x < width(); x++)
  215.             for (int y = 0; y < height(); y++)
  216.                 if (!this.get(x, y).equals(that.get(x, y))) return false;
  217.         return true;
  218.     }
  219.  
  220.  
  221.    /**
  222.      * Save the picture to a file in a standard image format.
  223.      * The filetype must be .png or .jpg.
  224.      */
  225.     public void save(String name) {
  226.         save(new File(name));
  227.     }
  228.  
  229.    /**
  230.      * Save the picture to a file in a standard image format.
  231.      */
  232.     public void save(File file) {
  233.         this.filename = file.getName();
  234.         if (frame != null) { frame.setTitle(filename); }
  235.         String suffix = filename.substring(filename.lastIndexOf('.') + 1);
  236.         suffix = suffix.toLowerCase();
  237.         if (suffix.equals("jpg") || suffix.equals("png")) {
  238.             try { ImageIO.write(image, suffix, file); }
  239.             catch (IOException e) { e.printStackTrace(); }
  240.         }
  241.         else {
  242.             System.out.println("Error: filename must end in .jpg or .png");
  243.         }
  244.     }
  245.  
  246.    /**
  247.      * Opens a save dialog box when the user selects "Save As" from the menu.
  248.      */
  249.     public void actionPerformed(ActionEvent e) {
  250.         FileDialog chooser = new FileDialog(frame,
  251.                              "Use a .png or .jpg extension", FileDialog.SAVE);
  252.         chooser.setVisible(true);
  253.         if (chooser.getFile() != null) {
  254.             save(chooser.getDirectory() + File.separator + chooser.getFile());
  255.         }
  256.     }
  257.  
  258.  
  259.    /**
  260.      * Test client. Reads a picture specified by the command-line argument,
  261.      * and shows it in a window on the screen.
  262.      */
  263.     public static void main(String[] args) {
  264.         Picture pic = new Picture(args[0]);
  265.         System.out.printf("%d-by-%d\n", pic.width(), pic.height());
  266.         pic.show();
  267.     }
  268.  
  269. }
Add Comment
Please, Sign In to add comment