LAB 10 – Modifying Pictures Using Loops (part 1 –Manipulating Pictures)
Lab Exercises
Topics
n To manipulate pictures
Exercises
4.2 Manipulating Pictures
Type in the following code in the Interactions window:
> String fileName;
> fileName = FileChooser.pickAFile(); // note that this pops up a window to select a jpg file
> Picture picture1;
> picture1 = new Picture(fileName);
> picture1.show();
>int width, height;
>width = picture1.getWidth();
>height = picture1.getHeight();
>System.out.println(“The pictures size is : ” + width + “ by “ + height);
//Get a pixel
>Pixel pixel1;
>pixel1 = picture1.getPixel (2,3);
>System.out.println(pixel1);
Try with different values for x and y.
//Get a row of pixels
>Pixel[] pixelArray;
>pixelArray = picture1.getPixels(); //notice the spelling of the method {is plural}
>System.out.println(pixelArray[5]);
//get the properties of a pixel
>System.out.println(pixel1.getX());
>System.out.println(pixel1.getY());
>System.out.println(pixel1.getColor());
>System.out.println(pixel1.getRed());
What was displayed?
You can also set the colors with
>pixel1.setRed(0); //Note this removes the red for this pixel
You can also create new colors, but should first import the Color class
> import java.awt.Color;
>Color color1;
>color1 = new Color (0, 100, 0); // light green
>System.out.println(color1);
>pixel1.setColor(color1);
>System.out.println(pixel1.getColor());
To see the changes, use repaint or show to redisplay the picture with the changes
>picture1.show();
You can adjust the colors by brightening or darkening the color:
>Color testColor;
>testColor = new Color(168, 131, 105);
>System.out.println(testColor);
>testColor = testColor.darker();
>System.out.println(testColor);
>testColor = testColor.brighter();
>System.out.println(testColor);
You can also pick a color:
> Color pickColor;
> pickColor = ColorChooser.pickAColor();
>System.out.println(pickColor);
You can write our modified picture to a file by typing:
>picture1.write(“newPicture.jpg”);
4.2.1 Exploring Pictures
Type in the following:
> import java.awt.Color;
> String fileName = "C:/intro-prog-java/mediasources/caterpillar.jpg";
> Picture pictureObj = new Picture(fileName);
> pictureObj.show();
> pictureObj.getPixel(10,100).setColor(Color.black);
> pictureObj.getPixel(11,100).setColor(Color.black);
> pictureObj.getPixel(12,100).setColor(Color.black);
> pictureObj.getPixel(13,100).setColor(Color.black);
> pictureObj.getPixel(14,100).setColor(Color.black);
> pictureObj.getPixel(15,100).setColor(Color.black);
> pictureObj.getPixel(16,100).setColor(Color.black);
> pictureObj.getPixel(17,100).setColor(Color.black);
> pictureObj.getPixel(18,100).setColor(Color.black);
> pictureObj.getPixel(19,100).setColor(Color.black);
> pictureObj.repaint();
> pictureObj.explore();