Lecture 38 (Tychonievich) - Images part 2

Lecture Date: Friday, April 17

Setup

For most of you, simply download ImageManipulation.zip and in Eclipse chose File → Import → Existing Project, selecting the .zip file.

For those who have an older version of Java, you can instead download multimedia.jar and in Eclipse make a new project in Eclipse right-click on the project name and select Build Path → Add External Archives, selecting the .jar file.

You’ll need any images you plan to use to be in your project folder, but not in your src/ folder.

Code Snippets

Load and Show
1
2
3
Picture p = new Picture("picture1.jpg");
p.setTitle("Picture number 1"); // optional
p.show();
Black and White
1
2
3
4
5
6
7
8
9
10
11
12
Picture p = new Picture("picture1.jpg");
for(int x = 0; x < p.getWidth(); x += 1) {
  for(int y = 0; y < p.getHeight(); y += 1) {
      if (p.getPixel(x, y).getAverage() > 130) {
          // could use getRed or getGreen or getBlue instead
          p.getPixel(x, y).setColor(new Color(255, 255, 255));
      } else {
          p.getPixel(x, y).setColor(new Color(0, 0, 0));
      }
  }
}
p.show();
Greyscale
1
2
3
4
5
6
7
8
Picture p = new Picture("picture1.jpg");
for(int x = 0; x < p.getWidth(); x += 1) {
  for(int y = 0; y < p.getHeight(); y += 1) {
      Pixel px = p.getPixel(x, y);
      px.setRed(px.getAverage());
  }
}
p.show();

From Lecture:

Code: