Skip to content Skip to navigation Skip to collection information

OpenStax_CNX

You are here: Home » Content » Object-Oriented Programming (OOP) with Java » Java3014: Cropping, Flipping, and Combining Pictures

Navigation

Table of Contents

Recently Viewed

This feature requires Javascript to be enabled.
 

Java3014: Cropping, Flipping, and Combining Pictures

Module by: R.G. (Dick) Baldwin. E-mail the author

Summary: Learn to crop, flip, and combine pictures.

Preface

This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP) using Java.

The program described in this module requires the use of the Guzdial-Ericson multimedia class library. You will find download, installation, and usage instructions for the library at Java OOP: The Guzdial-Ericson Multimedia Class Library .

Viewing tip

I recommend that you open another copy of this document in a separate browser window and use the following links to easily find and view the images and listings while you are reading about them.

Images

Listings

Preview

In this module, you will learn how to:

  • Work directly with individual pixels and keep track of coordinate values.
  • Copy a portion of one picture into a specific location in another picture.
  • Crop and flip a picture.

Program specifications

Write a program named Prob02 that uses the class definition shown in Listing 1 and Ericson's media library along with the image files named Prob02a.jpg and Prob02b.jpg to produce the three graphic output images shown in Image 1 , Image 2 , and Image 3 .

1
Image 1: Raw butterfly image.
This is an image of a butterfly that will be superimposed on a beach scene to form a composite image.
2
Image 2: Beach scene with student's name added.
This is an image of a beach scene that will be used to form a composite image.
3
Image 3: Composite image.
This is the composite image with the cropped and flipped images of the butterfly superimposed on the beach scene on each side of center.

May define new classes

You may define new classes as necessary to cause your program to behave as required, but you may not modify the class definition for the class named Prob02 given in Listing 1 .

The facing butterfly images

The two facing images of the butterflies in the final output picture are separated by two pixels and those two images as a pair are centered in the picture of the beach.

Required text output

In addition to the three output images mentioned above, your program must display your name and the other three lines of text shown in Image 4 on the command-line screen:

4
Image 4: Required text output.
Display your name here.
Picture, filename Prob02a.jpg height 118 width 100
Picture, filename Prob02b.jpg height 240 width 320
Picture, filename None height 101 width 77

General background information

This program copies a rectangular portion of a picture of a butterfly into a specific location in a picture of a beach.

The program also crops the butterfly picture to the same size as the portion that was copied into the beach picture and flips the cropped version to cause the butterfly to face left instead of facing right.

Then it copies the cropped and flipped image to a location two pixels to the right of the original copy of the butterfly in the beach image.

The two resulting images of the butterfly within the beach image are separated by two pixels, face one another, and are centered in the picture of the beach as shown in Image 3 .

Major evaluation areas

In order to successfully write this program, the student must, as a minimum be able to:

  • Work directly with individual pixels and keep track of coordinate values.
  • Copy a portion of one picture into a specific location in another picture.
  • Crop and flip a picture.

Discussion and sample code

Will discuss in fragments

I will discuss this program in fragments. A complete listing of the program is provided in Listing 10 near the end of the module.

The driver class named Prob02

The driver class containing the main method is shown in Listing 1 .

5
Listing 1: The driver class named Prob02.
import java.awt.Color;

public class Prob02{
  public static void main(String[] args){
    Picture[] pictures = new Prob02Runner().run();

    System.out.println(pictures[0]);
    System.out.println(pictures[1]);
    System.out.println(pictures[2]);
  }//end main method
}//end class Prob02

A reference to an array object

The call to the run method in Listing 1 may be new to you. This call expects to receive a reference to an array object of type Picture[] as a return value.

Save return value in variable named pictures

The return value from the run method is stored in the local reference variable named pictures .

Extract and print references to Picture objects

Then the reference variable is used to extract references to the individual Picture objects encapsulated in the array. Those references are passed to the println method causing the last three lines of text shown in Image 4 to be displayed on the command line screen.

Beginning of the Prob02Runner class

The class named Prob02Runner begins in Listing 2 , which shows the constructor for the class.

6
Listing 2: Beginning of the Prob02Runner class.
class Prob02Runner{

  public Prob02Runner(){//constructor
    System.out.println("Display your name here.");
  }//end constructor

The constructor simply causes the student's name to be displayed on the command line screen, producing the first line of output text shown in Image 4 .

Beginning of the run method

The run method, that was called in Listing 1 begins in Listing 3 .

7
Listing 3: Beginning of the run method.
  public Picture[] run(){
    Picture picA = new Picture("Prob02a.jpg");
    picA.explore();
    
    Picture picB = new Picture("Prob02b.jpg");
    picB.addMessage("Display your name here.",10,20);
    picB.explore();

    Picture picC = cropAndFlip(picA,4,5,80,105);

Listing 3 instantiates two Picture objects from image files and displays them by calling the explore method on each Picture object. In addition, the student's name is added near the upper-left corner of the beach image. This code results in the images shown in Image 1 and Image 2 .

Call the cropAndFlip method

Then Listing 3 calls the cropAndFlip method passing the reference to the butterfly image of Image 1, along with some other information as parameters. The return value is stored in a new local reference variable of type Picture named picC .

Put discussion of the run method on hold

I will put the discussion of the run method on temporary hold at this point and explain the method named cropAndFlip , which begins in Listing 4 .

Beginning of the cropAndFlip method

The cropAndFlip method crops a picture to the specified coordinate values and flips it around a vertical line at its center.

8
Listing 4: Beginning of the cropAndFlip method.

  private Picture cropAndFlip(Picture pic,
                              int x1,int y1,
                              int x2,int y2){
    Picture output = new Picture(x2-x1+1,y2-y1+1);

    int width = output.getWidth();
    
    Pixel pixel = null;
    Color color = null;

Incoming parameters

In addition to a reference to the picture to be processed, the method receives four incoming integer values as parameters. The parameters named x1 and y1 specify the coordinates of the upper-left corner of a rectangular area of the picture that is to be retained in the output.

The parameters named x2 and y2 specify the coordinates of the lower-right corner of the rectangular area of the picture that is to be retained in the output.

An empty Picture object

Listing 4 begins by creating an empty Picture object of the correct size to hold the cropped image. A reference to the empty picture is saved in the local reference variable named output .

Then Listing 4 gets and saves the width of the output picture.

Following this, Listing 4 declares two local working variables named pixel (of type Pixel ) and color (of type Color ) .

Process using nested loops

Listing 5 uses a pair of nested for loops to cause the output picture to be a cropped version of the picture received as an incoming parameter. The cropped image is flipped around its center.

9
Listing 5: Process using nested loops.
    for(int col = x1;col < (x2+1);col++){
      for(int row = y1;row < (y2+1);row++){
        color = pic.getPixel(col,row).getColor();
        pixel = output.getPixel(width-col+x1-1,row-y1);
        pixel.setColor(color);
      }//end inner loop
    }//end outer loop

    return output;
  }//end cropAndFlip method

The code in Listing 5 copies the pixel colors of the selected pixels of the incoming image to the pixels of the output image, flipping the image around its center line in the process.

Cropped and flipped version of the butterfly image

If you display the picture referred to by output in Listing 5 , you will get the image shown in Image 5 .

10
Image 5: Cropped and flipped version of the butterfly image.
This is an image of the butterfly that has been cropped to eliminate extraneous material and flipped horizontally.

Compare with the original butterfly picture

If you compare Image 5 with Image 1 , you will see that pixels on the outer edges of Image 1 have been discarded and the resulting image has been flipped around its centerline.

End of the cropAndFlip method

Image 5 returns a reference to the new image and ends the method named cropAndFlip . The returned value is stored in the variable named picC in Listing 3 .

Original image not modified

Note that the code in the cropAndFlip method does not modify the original image of the butterfly. Instead, it extracts pixel data from the original image to produce a new image. When control returns to the run method in Listing 3 , a reference to the new image is stored in the variable named picC .

Call the copyPictureWithCrop method from the run method

Control has now returned to the run method, picking up where Listing 3 left off. The next statement in the run method is shown in Listing 6 .

11
Listing 6: Call the copyPictureWithCrop method from the run method.
    copyPictureWithCrop(picA,picB,82,70,4,5,77,101);

Put the run method on hold again

Once again, I will put the run method on hold while I explain the method named copyPictureWithCrop , which begins in Listing 7 .

Beginning of the method named copyPictureWithCrop

The first two incoming parameters named source and dest are references to a source picture and a destination picture.

When the method is called in Listing 6 , the source picture is the original butterfly picture shown in Image 1 and the destination picture is the beach picture shown in Image 2 .

12
Listing 7: Beginning of the method named copyPictureWithCrop.
  private void copyPictureWithCrop(
           Picture source,
           Picture dest,
           int xOff,
           int yOff,
           int xCoor,
           int yCoor,
           int width,
           int height){

    //Confirm that source will fit in destination
    if(((width+xOff) <= dest.getWidth()) &&
         ((height+yOff) <= dest.getHeight())){
         
      Pixel pixel = null;
      Color color = null;

Copy source to destination

The method named copyPictureWithCrop copies part of the source picture into the destination picture with an offset on both axes after first confirming that the part will fit. The method does nothing if the part won't fit.

The copy process causes selected pixel colors in the destination picture to be replaced by pixel colors from the source picture.

The offset values

The next two parameters named xOff and yOff in Listing 7 specify the location in the destination picture where the upper-left corner of the cropped source picture is to be located.

The statement in Listing 6 passes the values (82,70) for these two values. This is the location of the upper left corner of the left-most butterfly image in Image 3 .

Note:

Not really cropped

For clarity, I will refer to this as a cropped source picture even though the program doesn't actually save a cropped version of the picture as was the case with the cropAndFlip method.

The program simply copies a rectangular portion of the source picture into the destination picture.

Upper-left cropping corner

The parameters named xCoor and yCoor in Listing 7 specify the upper-left corner of the rectangular area of pixels that is to be preserved when the source image is cropped.

Coordinate values of (4,5) are passed for these two values when the method is called in Listing 6 .

Same values as Listing 3

Note that these are the same two values that were passed for this purpose when the cropAndFlip method was called in Listing 3 .

Two ways to specify a rectangle

There are two commonly used ways to specify a rectangular area in programming. One way is to specify the coordinates of the upper-left and bottom right corners. This is the approach used in the cropAndFlip method in Listing 4 .

The other way is to specify the coordinates of the upper-left corner and then to specify the width and the height. This is the approach used in the copyPictureWithCrop method in Listing 7 .

The width and height parameters

The parameters named width and height in Listing 7 specify the width and height of the rectangular area of pixels that is to be preserved when the source picture is cropped.

If you compare the width and height parameter values passed in Listing 6 with the coordinate values passed in Listing 3 , you will see that the same rectangular area of the butterfly image is being preserved after cropping in both cases.

Confirm that the cropped image will fit

Listing 7 begins by confirming that the cropped rectangular area of the source picture will fit within the destination picture when placed at the specified location. If the conditional clause of the if statement returns true, then the code in the body of the statement will be executed. If not, control bypasses the body of the if statement and the source picture will not be copied into the destination picture.

Process using nested for loops

As was the case in Listing 4 , Listing 7 declares two working variables named pixel and color .

The variables named pixel and color are used along with various parameter values in the pair of nested for loops shown in Listing 8 to crop the source picture and to copy the cropped source picture into the destination picture at the specified location.

13
Listing 8: Process using nested loops.
      for(int col = 0;col < width;col++){
        for(int row = 0;row < height;row++){
          color = source.getPixel(
                      col + xCoor,row + yCoor).getColor();
          pixel = dest.getPixel(col+xOff,row+yOff);
          pixel.setColor(color);
        }//end inner loop
      }//end outer loop
      
    }//end if
    
  }//end copyPictureWithCrop method
  
}//end class Prob02Runner

Not as complicated as it looks

Although the arithmetic operations involved in Listing 8 can be daunting, the code in Listing 8 is doing nothing more than replacing selected pixel colors in the destination picture with selected pixel colors from the source picture.

Partially complete version of the output picture.

If you were to display the destination picture before returning control back to the run method in Listing 8 , you would see the image shown in Image 6 .

14
Image 6: Partially complete version of the output picture.
This image shows a cropped version of the original butterfly image superimposed on the beach scene immediately to the left of center.

At this point, only one cropped version of the butterfly image has been copied into the beach image.

Return control to the run method

The copyPictureWithCrop method terminates in Listing 8 and returns control to the run method, picking up where Listing 6 left off.

The remainder of the run method

The remainder of the run method is shown in Listing 9 .

15
Listing 9: The remainder of the run method.
    copyPictureWithCrop(picC,picB,161,70,0,0,77,101);

    picB.explore();

    Picture[] output = {picA,picB,picC};
    return output;
  }//end run

Call the copyPictureWithCrop method again

Listing 9 begins by calling the copyPictureWithCrop method again. This time, however, the picture shown in Image 5 is passed as the source image with the same picture as before being passed as the destination image.

The offset coordinates

In this case, the offset coordinate values specify the upper-left corner of the right-most butterfly image in Image 3 .

The cropping parameters

The final four parameters that are passed in Listing 9 specify that the entire source picture is to be copied into the destination picture.

Display the destination picture

When the copyPictureWithCrop method returns, Listing 9 calls the explore method to display the current state of the destination picture. The result is shown in Image 3 .

A new array object

Finally, Listing 9 instantiates a new array object, populates it with references to three Picture objects, and returns control to the main method code in Listing 1 returning a reference to the array object in the process.

The code in Listing 1 saves the reference to the array object in the variable named pictures .

Pass Picture object references to println method

Then Listing 1 extracts and passes each of the three Picture object references to the println method causing the last three lines of text shown in Image 4 to be displayed on the command-line screen.

The second line of output text ( picA ) describes the raw butterfly image shown in Image 1 .

The third line of output text for ( picB ) describes the beach scene shown in Image 2 and Image 3 .

The last line of output text ( picC ) describes the cropped and flipped version of the butterfly image shown in Image 5 .

Run the program

I encourage you to copy the code from Listing 10 . Compile the code and execute it. Experiment with the code, making changes, and observing the results of your changes. Make certain that you can explain why your changes behave as they do.

Click here and here to download the two required input image files.

Summary

In this module, you learned how to:

  • Work directly with individual pixels and keep track of coordinate values.
  • Copy a portion of one picture into a specific location in another picture.
  • Crop and flip a picture.

What's next?

You will l earn to write a program to do green-screen processing in the next module.

Online video links

Select the following links to view online video lectures on the material in this module.

Miscellaneous

This section contains a variety of miscellaneous information.

Note:

Housekeeping material
  • Module name: Java OOP: Cropping, Flipping, and Combining Pictures
  • File: Java3014.htm
  • Published: 08/01/12
  • Revised: 02/14/13

Note:

Disclaimers:

Financial : Although the Connexions site makes it possible for you to download a PDF file for this module at no charge, and also makes it possible for you to purchase a pre-printed version of the PDF file, you should be aware that some of the HTML elements in this module may not translate well into PDF.

I also want you to know that, I receive no financial compensation from the Connexions website even if you purchase the PDF version of the module.

In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle books, and placed them for sale on Amazon.com showing me as the author. I neither receive compensation for those sales nor do I know who does receive compensation. If you purchase such a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it was made and published without my prior knowledge.

Affiliation : I am a professor of Computer Information Technology at Austin Community College in Austin, TX.

Complete program listing

A complete listing of the program discussed in this module is shown in Listing 10 below.

16
Listing 10: Complete program listing.
/*File Prob02 Copyright 2008 R.G.Baldwin
Revised 12/16/08
*********************************************************/
import java.awt.Color;

public class Prob02{
  public static void main(String[] args){
    Picture[] pictures = new Prob02Runner().run();

    System.out.println(pictures[0]);
    System.out.println(pictures[1]);
    System.out.println(pictures[2]);
  }//end main method
}//end class Prob02
//======================================================//

class Prob02Runner{

  public Prob02Runner(){//constructor
    System.out.println("Display your name here.");
  }//end constructor
  //----------------------------------------------------//

  public Picture[] run(){
    Picture picA = new Picture("Prob02a.jpg");
    picA.explore();
    Picture picB = new Picture("Prob02b.jpg");
    picB.addMessage("Display your name here.",10,20);
    picB.explore();

    Picture picC = cropAndFlip(picA,4,5,80,105);

    copyPictureWithCrop(picA,picB,82,70,4,5,77,101);
    copyPictureWithCrop(picC,picB,161,70,0,0,77,101);


    picB.explore();

    Picture[] output = {picA,picB,picC};
    return output;
  }//end run
  //----------------------------------------------------//

  //Crops a picture to the specified coordinate values and
  // flips it around a vertical line at its center.
  private Picture cropAndFlip(Picture pic,int x1,int y1,
                              int x2,int y2){
    Picture output = new Picture(x2-x1+1,y2-y1+1);

    int width = output.getWidth();
    Pixel pixel = null;
    Color color = null;
    for(int col = x1;col < (x2+1);col++){
      for(int row = y1;row < (y2+1);row++){
        color = pic.getPixel(col,row).getColor();
        pixel = output.getPixel(width-col+x1-1,row-y1);
        pixel.setColor(color);
      }//end inner loop
    }//end outer loop

    return output;
  }//end crop and flip
  //----------------------------------------------------//

  //Copies part of the source picture into the destination
  // picture with an offset on both axes after first
  // confirming that the part will fit. Does nothing if it
  // won't fit.
  private void copyPictureWithCrop(
           Picture source,Picture dest,int xOff,
                                       int yOff,
                                       int xCoor,
                                       int yCoor,
                                       int width,
                                       int height){

    //Confirm that source will fit in destination
    if(((width+xOff) <= dest.getWidth()) &&
         ((height+yOff) <= dest.getHeight())){
      Pixel pixel = null;
      Color color = null;
      for(int col = 0;col < width;col++){
        for(int row = 0;row < height;row++){
          color = source.getPixel(
                      col + xCoor,row + yCoor).getColor();
          pixel = dest.getPixel(col+xOff,row+yOff);
          pixel.setColor(color);
        }//end inner loop
      }//end outer loop
    }//end if
  }//end copyPictureWithCrop method
}//end class Prob02Runner

-end-

Collection Navigation

Content actions

Download:

Collection as:

EPUB (?)

What is an EPUB file?

EPUB is an electronic book format that can be read on a variety of mobile devices.

Downloading to a reading device

For detailed instructions on how to download this content's EPUB to your specific device, click the "(?)" link.

| More downloads ...

Module as:

PDF | EPUB (?)

What is an EPUB file?

EPUB is an electronic book format that can be read on a variety of mobile devices.

Downloading to a reading device

For detailed instructions on how to download this content's EPUB to your specific device, click the "(?)" link.

| More downloads ...

Add:

Collection to:

My Favorites (?)

'My Favorites' is a special kind of lens which you can use to bookmark modules and collections. 'My Favorites' can only be seen by you, and collections saved in 'My Favorites' can remember the last module you were on. You need an account to use 'My Favorites'.

| A lens I own (?)

Definition of a lens

Lenses

A lens is a custom view of the content in the repository. You can think of it as a fancy kind of list that will let you see content through the eyes of organizations and people you trust.

What is in a lens?

Lens makers point to materials (modules and collections), creating a guide that includes their own comments and descriptive tags about the content.

Who can create a lens?

Any individual member, a community, or a respected organization.

What are tags? tag icon

Tags are descriptors added by lens makers to help label content, attaching a vocabulary that is meaningful in the context of the lens.

| External bookmarks

Module to:

My Favorites (?)

'My Favorites' is a special kind of lens which you can use to bookmark modules and collections. 'My Favorites' can only be seen by you, and collections saved in 'My Favorites' can remember the last module you were on. You need an account to use 'My Favorites'.

| A lens I own (?)

Definition of a lens

Lenses

A lens is a custom view of the content in the repository. You can think of it as a fancy kind of list that will let you see content through the eyes of organizations and people you trust.

What is in a lens?

Lens makers point to materials (modules and collections), creating a guide that includes their own comments and descriptive tags about the content.

Who can create a lens?

Any individual member, a community, or a respected organization.

What are tags? tag icon

Tags are descriptors added by lens makers to help label content, attaching a vocabulary that is meaningful in the context of the lens.

| External bookmarks