LAB 13 - Modifying Pictures in a Matrix (part 1 - Copying Pixels)
Topics
n To copy pixels in a matrix using nested loops
5.1 Copying Pixels
Type in the following code in the Program window (changing the comments):
/* Program that modifies pictures using nested loops
* Picture and Pixel classes are defined in bookClasses developed
* at Georgia Tech by Mark Guzdial / Barbara Ericson
*
* @author Wayne Summers
* @date Sept. 19, 2007
*/
public class ModifyPictures
{
public static void main(String[] args)
{
String fileName;
fileName = FileChooser.pickAFile(); // note that this pops up a window to select a jpg file
Picture pic;
pic = new Picture(fileName);
// calls to methods that manipulate images go here
pic.show();
}
}
5.1.1 Looping Across the Pixels with a Nested Loop
5.1.2 Mirroring a Picture (vertical)
i) Type in the following code in the Program window below the main method and before the last }:
/**
* Method that mirrors the leftside of a picture to the rightside
* @param pict - picture Object to be modified
*/
public static void mirrorVertical(Picture pict)
{
int mirrorPoint = pict.getWidth() / 2;
Pixel leftPixel = null;
Pixel rightPixel = null;
// loop through the rows
for (int y = 0; y < pict.getHeight(); y++)
{
// loop from 0 to just before the mirror point
for (int x = 0; x < mirrorPoint; x++)
{
leftPixel = pict.getPixel(x, y);
rightPixel = pict.getPixel(pict.getWidth() – 1 – x, y);
rightPixel.setColor(leftPixel.getColor());
}
}
}
ii) Type in the following code in the Program window in the main method and before the pic.show();
mirrorVertical(pic);
iii) Test your program.
5.1.2 Mirroring a Picture (horizontal)
i) Type in the following code in the Program window below the main method and before the last }:
/**
* Method that mirrors the top of a picture to the bottom
* @param pict - picture Object to be modified
*/
public static void mirrorHorizontal(Picture pict)
{
int height = pict.getHeight();
int width = pict.getWidth();
int mirrorPoint = height / 2;
Pixel topPixel = null;
Pixel bottomPixel = null;
// loop through the columns
for (int x = 0; x < width; x++)
{
// loop from 0 to just before the mirror point
for (int y = 0; y < mirrorPoint; y++)
{
topPixel = pict.getPixel(x, y);
bottomPixel = pict.getPixel(x, height - 1 - y);
bottomPixel.setColor(topPixel.getColor());
}
}
}
ii) Type in the following code in the Program window in the main method and before the pic.show();
mirrorHorizontal (pic);
iii) Test your program.
QUESTIONS:
Write a program that uses a method that calls both mirrorHorizontal and mirrorVertical.
Does it matter which order you call the two methods?
CHALLENGE: Write a method that mirrors across the diagonal.
Submit the .java file and the answer to the question through the DropBox in WebCT.