Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

/****************************************************************************** * Compilation: javac Picture.java * Execution: java Picture imagename * Dependencies: none * * Data type for manipulating individual pixels of an image. The

image text in transcribed

/****************************************************************************** * Compilation: javac Picture.java * Execution: java Picture imagename * Dependencies: none * * Data type for manipulating individual pixels of an image. The original * image can be read from a file in jpg, gif, or png format, or the * user can create a blank image of a given size. Includes methods for * displaying the image in a window on the screen or saving to a file. * * % java Picture mandrill.jpg * * Remarks * ------- * - pixel (x, y) is column x and row y, where (0, 0) is upper left * * - see also GrayPicture.java for a grayscale version * ******************************************************************************/

import java.awt.Color; import java.awt.FileDialog; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.net.URL; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.KeyStroke;

/** * This class provides methods for manipulating individual pixels of * an image. The original image can be read from a {@code .jpg}, {@code .gif}, * or {@code .png} file or the user can create a blank image of a given size. * This class includes methods for displaying the image in a window on * the screen or saving it to a file. *

* Pixel (col, row) is column col and row row. * By default, the origin (0, 0) is the pixel in the top-left corner, * which is a common convention in image processing. * The method {@code setOriginLowerLeft()} change the origin to the lower left. *

* For additional documentation, see * Section 3.1 of * Computer Science: An Interdisciplinary Approach * by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ public final class Picture implements ActionListener { private BufferedImage image; // the rasterized image private JFrame frame; // on-screen view private String filename; // name of file private boolean isOriginUpperLeft = true; // location of origin private final int width, height; // width and height

/** * Initializes a blank {@code width}-by-{@code height} picture, with {@code width} columns * and {@code height} rows, where each pixel is black. * * @param width the width of the picture * @param height the height of the picture * @throws IllegalArgumentException if {@code width} is negative * @throws IllegalArgumentException if {@code height} is negative */ public Picture(int width, int height) { if (width

/** * Initializes a new picture that is a deep copy of the argument picture. * * @param picture the picture to copy * @throws IllegalArgumentException if {@code picture} is {@code null} */ public Picture(Picture picture) { if (picture == null) throw new IllegalArgumentException("constructor argument is null");

width = picture.width(); height = picture.height(); image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); filename = picture.filename; for (int col = 0; col

/** * Initializes a picture by reading from a file or URL. * * @param filename the name of the file (.png, .gif, or .jpg) or URL. * @throws IllegalArgumentException if cannot read image * @throws IllegalArgumentException if {@code filename} is {@code null} */ public Picture(String filename) { if (filename == null) throw new IllegalArgumentException("constructor argument is null");

this.filename = filename; try { // try to read from file in working directory File file = new File(filename); if (file.isFile()) { image = ImageIO.read(file); }

// now try to read from file in same directory as this .class file else { URL url = getClass().getResource(filename); if (url == null) { url = new URL(filename); } image = ImageIO.read(url); }

if (image == null) { throw new IllegalArgumentException("could not read image file: " + filename); }

width = image.getWidth(null); height = image.getHeight(null); } catch (IOException ioe) { throw new IllegalArgumentException("could not open image file: " + filename, ioe); } }

/** * Initializes a picture by reading in a .png, .gif, or .jpg from a file. * * @param file the file * @throws IllegalArgumentException if cannot read image * @throws IllegalArgumentException if {@code file} is {@code null} */ public Picture(File file) { if (file == null) throw new IllegalArgumentException("constructor argument is null");

try { image = ImageIO.read(file); } catch (IOException ioe) { throw new IllegalArgumentException("could not open file: " + file, ioe); } if (image == null) { throw new IllegalArgumentException("could not read file: " + file); } width = image.getWidth(null); height = image.getHeight(null); filename = file.getName(); }

/** * Returns a JLabel containing this picture, for embedding in a JPanel, * JFrame or other GUI widget. * * @return the {@code JLabel} */ public JLabel getJLabel() { if (image == null) return null; // no image available ImageIcon icon = new ImageIcon(image); return new JLabel(icon); }

/** * Sets the origin to be the upper left pixel. This is the default. */ public void setOriginUpperLeft() { isOriginUpperLeft = true; }

/** * Sets the origin to be the lower left pixel. */ public void setOriginLowerLeft() { isOriginUpperLeft = false; }

/** * Displays the picture in a window on the screen. */ public void show() {

// create the GUI for viewing the image if needed if (frame == null) { frame = new JFrame();

JMenuBar menuBar = new JMenuBar(); JMenu menu = new JMenu("File"); menuBar.add(menu); JMenuItem menuItem1 = new JMenuItem(" Save... "); menuItem1.addActionListener(this); menuItem1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); menu.add(menuItem1); frame.setJMenuBar(menuBar);

frame.setContentPane(getJLabel()); // f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setTitle(filename); frame.setResizable(false); frame.pack(); frame.setVisible(true); }

// draw frame.repaint(); }

/** * Returns the height of the picture. * * @return the height of the picture (in pixels) */ public int height() { return height; }

/** * Returns the width of the picture. * * @return the width of the picture (in pixels) */ public int width() { return width; }

private void validateRow(int row) { if (row = height()) throw new IndexOutOfBoundsException("row must be between 0 and " + (height() - 1) + ": " + row); }

private void validateCol(int col) { if (col = width()) throw new IndexOutOfBoundsException("col must be between 0 and " + (width() - 1) + ": " + col); }

/** * Returns the color of pixel ({@code col}, {@code row}). * * @param col the column index * @param row the row index * @return the color of pixel ({@code col}, {@code row}) * @throws IndexOutOfBoundsException unless both {@code 0

/** * Sets the color of pixel ({@code col}, {@code row}) to given color. * * @param col the column index * @param row the row index * @param color the color * @throws IndexOutOfBoundsException unless both {@code 0

/** * Returns true if this picture is equal to the argument picture. * * @param other the other picture * @return {@code true} if this picture is the same dimension as {@code other} * and if all pixels have the same color; {@code false} otherwise */ public boolean equals(Object other) { if (other == this) return true; if (other == null) return false; if (other.getClass() != this.getClass()) return false; Picture that = (Picture) other; if (this.width() != that.width()) return false; if (this.height() != that.height()) return false; for (int col = 0; col

/** * This operation is not supported because pictures are mutable. * * @return does not return a value * @throws UnsupportedOperationException if called */ public int hashCode() { throw new UnsupportedOperationException("hashCode() is not supported because pictures are mutable"); }

/** * Saves the picture to a file in a standard image format. * The filetype must be .png or .jpg. * * @param filename the name of the file * @throws IllegalArgumentException if {@code name} is {@code null} */ public void save(String filename) { if (filename == null) throw new IllegalArgumentException("argument to save() is null"); save(new File(filename)); }

/** * Saves the picture to a file in a PNG or JPEG image format. * * @param file the file * @throws IllegalArgumentException if {@code file} is {@code null} */ public void save(File file) { if (file == null) throw new IllegalArgumentException("argument to save() is null"); filename = file.getName(); if (frame != null) frame.setTitle(filename); String suffix = filename.substring(filename.lastIndexOf('.') + 1); if ("jpg".equalsIgnoreCase(suffix) || "png".equalsIgnoreCase(suffix)) { try { ImageIO.write(image, suffix, file); } catch (IOException e) { e.printStackTrace(); } } else { System.out.println("Error: filename must end in .jpg or .png"); } }

/** * Opens a save dialog box when the user selects "Save As" from the menu. */ @Override public void actionPerformed(ActionEvent e) { FileDialog chooser = new FileDialog(frame, "Use a .png or .jpg extension", FileDialog.SAVE); chooser.setVisible(true); if (chooser.getFile() != null) { save(chooser.getDirectory() + File.separator + chooser.getFile()); } }

/** * Unit tests this {@code Picture} data type. * Reads a picture specified by the command-line argument, * and shows it in a window on the screen. * * @param args the command-line arguments */ public static void main(String[] args) { Picture picture = new Picture(args[0]); System.out.printf("%d-by-%d ", picture.width(), picture.height()); picture.show(); }

}

reduceWidth (double x) Returns a new Picture whose width is [x times M]. Note that the type of this method must be Picture. Your method must use the algorithm described earlier to reduce the image width. And your method must use the static method minCostVC to compute the vertical cut. Otherwise, you will receive zero credit. reduceWidth (double x) Returns a new Picture whose width is [x times M]. Note that the type of this method must be Picture. Your method must use the algorithm described earlier to reduce the image width. And your method must use the static method minCostVC to compute the vertical cut. Otherwise, you will receive zero credit

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Essential Data Protection For Estate Agencies In Singapore 2024

Authors: Yang Yen Thaw Yt

1st Edition

B0CQK79WD3, 979-8872095392

Students also viewed these Databases questions