Class Picture
- Object
-
- edu.princeton.cs.algs4.Picture
-
- All Implemented Interfaces:
ActionListener
,EventListener
public final class Picture extends Object implements ActionListener
Overview. The
Picture
class provides a basic capability for manipulating the individual pixels of an image. You can either create a blank image (of a given dimension) or read an image in a supported file format (typically JPEG, PNG, GIF TIFF, and BMP). This class also includes methods for displaying the image in a window and saving it to a file.Use in the curriculum. The
Picture
class is intended for use in the curriculum once objects are introduced. TheStdPicture
class is intended for earlier use in the curriculum, before objects (but it can support only one picture at a time). SeeGrayscalePicture
for a version that supports grayscale images.Getting started. To use this class, you must have
Picture
in your Java classpath. Here are three possible ways to do this:- If you ran our autoinstaller, use the commands
javac-introcs
andjava-introcs
(orjavac-algs4
andjava-algs4
) when compiling and executing. These commands addstdlib.jar
(oralgs4.jar
) to the Java classpath, which provides access toPicture
. - Download stdlib.jar (or algs4.jar) and add it to the Java classpath.
- Download StdPicture.java and Picture.java and put them in the working directory.
As a test, cut-and-paste the following short program into your editor:
public class TestPicture { public static void main(String[] args) { Picture picture = new Picture("https://introcs.cs.princeton.edu/java/stdlib/mandrill.jpg"); picture.show(); } }
If you compile and execute the program, you should see a picture of a mandrill (a colorful monkey native to west-central Africa) in a window.
Anatomy of an image. An image is a width-by-height grid of pixels, with pixel (0, 0) in the upper-left corner. Each pixel has a color that is represented using the RGB color model, which specifies the levels of red (R), green (G), and blue (B) on an integer scale from 0 to 255.
Creating pictures. You can use the following constructors to create new
Picture
objects:The first constructor read an image in a supported file format (typically JPEG, PNG, GIF TIFF, and BMP) and initializes the picture to that image. The second constructor creates a width-by-height picture, with each pixel black.
Getting and setting the colors of the individual pixels. You can use the following methods to get and set the color of a specified pixel:
The first method returns the color of pixel (col, row) as a
Color
object. The second method set the color of pixel (col, row) to the specified color.Iterating over the pixels. A common operation in image processing is to iterate over and process all of the pixels in an image. Here is a prototypical example that creates a grayscale version of a color image, using the NTSC formula Y = 0.299r + 0.587g + 0.114b. Note that if the red, green, and blue components of an RGB color are all equal, the color is a shade of gray.
Picture picture = new Picture("https://introcs.cs.princeton.edu/java/stdlib/mandrill.jpg"); Picture grayscale = new Picture(picture.width(), picture.height()); for (int col = 0; col < picture.width(); col++) { for (int row = 0; row < picture.height(); row++) { Color color = picture.get(col, row); int r = color.getRed(); int g = color.getGreen(); int b = color.getBlue(); int y = (int) (Math.round(0.299*r + 0.587*g + 0.114*b)); Color gray = new Color(y, y, y); grayscale.set(col, row, gray); } } picture.show(); grayscale.show();
Saving files. The
Picture
class supports writing images to a supported file format (typically JPEG, PNG, GIF TIFF, and BMP). Note that some file formats (such as JPEG and BMP) do not support transparency. You can save the picture to a file using these two methods:Alternatively, you can save the picture interactively by using the menu option File → Save from the picture window.
Transparency. Both the
Color
andPicture
classes support transparency, using the alpha channel. The alpha value defines the transparency of a color, with 0 corresponding to completely transparent and 255 to completely opaque. If transparency is not explicitly used, all alpha values are 255.32-bit color. Sometimes it is more convenient (or efficient) to manipulate the color of a pixel as a single 32-bit integers instead of four 8-bit components. The following methods support this:
The red (R), green (G), and blue (B) components are encoded using the least significant 24 bits. Given a 32-bit
int
encoding the color, the following code extracts the ARGB components:
Given the ARGB components (8-bits each) of a color, the following statement packs it into a 32-bitint a = (rgb >> 24) & 0xFF; int r = (rgb >> 16) & 0xFF; int g = (rgb >> 8) & 0xFF; int b = (rgb >> 0) & 0xFF;
int
:int argb = (a << 24) | (r << 16) | (g << 8) | (b << 0);
Coordinates. Pixel (col, row) is column col and row row. By default, the origin (0, 0) is the pixel in the upper-left corner. These are common conventions in image processing and consistent with Java's
BufferedImage
data type. The following two methods allow you to change this convention:Memory usage. A W-by-H picture uses ~ 4 W H bytes of memory, since the color of each pixel is encoded as a 32-bit
int
.Additional documentation. For additional documentation, see Section 3.1 of Computer Science: An Interdisciplinary Approach by Robert Sedgewick and Kevin Wayne.
- Author:
- Robert Sedgewick, Kevin Wayne
-
-
Constructor Summary
Constructors Constructor Description Picture(int width, int height)
Creates awidth
-by-height
picture, withwidth
columns andheight
rows, where each pixel is black.Picture(Picture picture)
Creates a new picture that is a deep copy of the argument picture.Picture(File file)
Creates a picture by reading the image from a JPEG, PNG, or GIF file.Picture(String filename)
Creates a picture by reading a JPEG, PNG, or GIF image from a file or URL.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description void
actionPerformed(ActionEvent e)
Opens a save dialog box when the user selects "Save As" from the menu.boolean
equals(Object other)
Returns true if this picture is equal to the argument picture.Color
get(int col, int row)
JLabel
getJLabel()
int
getRGB(int col, int row)
Returns the color of pixel (col
,row
) as anint
.int
hashCode()
This operation is not supported because pictures are mutable.int
height()
Returns the height of the picture.void
hide()
Hides the window on the screen.boolean
isVisible()
Is the window containing the picture visible?static void
main(String[] args)
Unit tests thisPicture
data type.void
save(File file)
Saves the picture to a file in a supported format (typically JPEG, PNG, GIF TIFF, and BMP).void
save(String filename)
Saves the picture to a file in a supported file format (typically JPEG, PNG, GIF TIFF, and BMP).void
set(int col, int row, Color color)
Sets the color of pixel (col
,row
) to given color.void
setOriginLowerLeft()
Sets the origin to be the lower left pixel.void
setOriginUpperLeft()
Sets the origin to be the upper left pixel.void
setRGB(int col, int row, int rgb)
Sets the color of pixel (col
,row
) to given color.void
setTitle(String title)
Sets the title of this picture.void
show()
Displays the picture in a window on the screen.String
toString()
Returns a string representation of this picture.int
width()
Returns the width of the picture.
-
-
-
Constructor Detail
-
Picture
public Picture(int width, int height)
Creates awidth
-by-height
picture, withwidth
columns andheight
rows, where each pixel is black.- Parameters:
width
- the width of the pictureheight
- the height of the picture- Throws:
IllegalArgumentException
- ifwidth
is negative or zeroIllegalArgumentException
- ifheight
is negative or zero
-
Picture
public Picture(Picture picture)
Creates a new picture that is a deep copy of the argument picture.- Parameters:
picture
- the picture to copy- Throws:
IllegalArgumentException
- ifpicture
isnull
-
Picture
public Picture(String filename)
Creates a picture by reading a JPEG, PNG, or GIF image from a file or URL. The filetype extension must be.jpg
,.png
, or.gif
.- Parameters:
filename
- the name of the file or URL- Throws:
IllegalArgumentException
- if cannot read imageIllegalArgumentException
- ifname
isnull
-
Picture
public Picture(File file)
Creates a picture by reading the image from a JPEG, PNG, or GIF file.- Parameters:
file
- the file- Throws:
IllegalArgumentException
- if cannot read imageIllegalArgumentException
- iffile
isnull
-
-
Method Detail
-
getJLabel
public JLabel getJLabel()
- Returns:
- the
JLabel
-
setOriginUpperLeft
public void setOriginUpperLeft()
Sets the origin to be the upper left pixel. This is the default.
-
setOriginLowerLeft
public void setOriginLowerLeft()
Sets the origin to be the lower left pixel.
-
show
public void show()
Displays the picture in a window on the screen.
-
hide
public void hide()
Hides the window on the screen.
-
isVisible
public boolean isVisible()
Is the window containing the picture visible?- Returns:
true
if the picture is visible, andfalse
otherwise
-
height
public int height()
Returns the height of the picture.- Returns:
- the height of the picture (in pixels)
-
width
public int width()
Returns the width of the picture.- Returns:
- the width of the picture (in pixels)
-
get
public Color get(int col, int row)
- Parameters:
col
- the column indexrow
- the row index- Returns:
- the color of pixel (
col
,row
) - Throws:
IllegalArgumentException
- unless both0 <= col < width
and0 <= row < height
-
getRGB
public int getRGB(int col, int row)
Returns the color of pixel (col
,row
) as anint
. Using this method can be more efficient thanget(int, int)
because it does not create aColor
object.- Parameters:
col
- the column indexrow
- the row index- Returns:
- the integer representation of the color of pixel (
col
,row
) - Throws:
IllegalArgumentException
- unless both0 <= col < width
and0 <= row < height
-
set
public void set(int col, int row, Color color)
Sets the color of pixel (col
,row
) to given color.- Parameters:
col
- the column indexrow
- the row indexcolor
- the color- Throws:
IllegalArgumentException
- unless both0 <= col < width
and0 <= row < height
IllegalArgumentException
- ifcolor
isnull
-
setRGB
public void setRGB(int col, int row, int rgb)
Sets the color of pixel (col
,row
) to given color.- Parameters:
col
- the column indexrow
- the row indexrgb
- the integer representation of the color- Throws:
IllegalArgumentException
- unless both0 <= col < width
and0 <= row < height
-
equals
public boolean equals(Object other)
Returns true if this picture is equal to the argument picture.
-
toString
public String toString()
Returns a string representation of this picture. The result is awidth
-by-height
matrix of pixels, where the color of a pixel is represented using 6 hex digits to encode the red, green, and blue components.
-
hashCode
public int hashCode()
This operation is not supported because pictures are mutable.- Overrides:
hashCode
in classObject
- Returns:
- does not return a value
- Throws:
UnsupportedOperationException
- if called
-
setTitle
public void setTitle(String title)
Sets the title of this picture.- Parameters:
title
- the title- Throws:
IllegalArgumentException
- iftitle
isnull
-
save
public void save(String filename)
Saves the picture to a file in a supported file format (typically JPEG, PNG, GIF TIFF, and BMP). If the file format does not support transparency (such as JPEG or BMP), it will be converted to be opaque (with purely transparent pixels converted to black).- Parameters:
filename
- the name of the file- Throws:
IllegalArgumentException
- iffilename
isnull
IllegalArgumentException
- iffilename
is the empty string
-
save
public void save(File file)
Saves the picture to a file in a supported format (typically JPEG, PNG, GIF TIFF, and BMP).- Parameters:
file
- the file- Throws:
IllegalArgumentException
- iffile
isnull
-
actionPerformed
public void actionPerformed(ActionEvent e)
Opens a save dialog box when the user selects "Save As" from the menu.- Specified by:
actionPerformed
in interfaceActionListener
-
main
public static void main(String[] args)
Unit tests thisPicture
data type. Reads a picture specified by the command-line argument, and shows it in a window on the screen.- Parameters:
args
- the command-line arguments
-
-