CS1026a Computer Science Fundamentals I (Java)

Fall 2009
Returning pictures from methods (topic 11)


On the slides of topic 11, we saw a method that creates a new picture by copying it from the current picture and reducing the amount of red; then, it returns the new picture.

public Picture decreaseRed()
{
  Picture newPic = new Picture(this.getWidth(), this.getHeight());
  for (int x = 0; x < this.getWidth(); x++)
  {
    for (int y = 0; y < this.getHeight(); y++)
    {
      Pixel pixSource = this.getPixel(x, y);
      Pixel pixDest = newPic.getPixel(x, y);
      pixDest.setRed(pixSource.getRed()/2);
      pixDest.setGreen(pixSource.getGreen());
      pixDest.setBlue(pixSource.getBlue());
    }
  }
  return newPic;
}

A sample usage is

String fileName = FileChooser.pickAFile();
Picture pic = new Picture(fileName);
Picture newPic = pic.decreaseRed();
newPic.show();

It was pointed out in class that one can achieve the same effect using the method we had before. Here is the older version of decreaseRed, which simply decreases the red amount of the current picture.

public void decreaseRedOlder()
{
  for (int x = 0; x < this.getWidth(); x++)
  {
    for (int y = 0; y < this.getHeight(); y++)
    {
      Pixel pixSource = this.getPixel(x, y);
      pixSource.setRed(pixSource.getRed()/2);
    }
  }
}

We will also need a method to copy a picture, called void copyPicture(Picture source); it is given here. Then, the following sample code achieves the same effect as before.

String fileName = FileChooser.pickAFile();
Picture pic = new Picture(fileName);
Picture newPic = new Picture(pic.getWidth(), pic.getHeight());
newPic.copyPicture(pic);
newPic.decreaseRedOlder();
newPic.show();