Skip to content Skip to navigation Skip to collection information

OpenStax-CNX

You are here: Home » Content » Object-Oriented Programming (OOP) with Java » Java3028: Clipping Images

Navigation

Table of Contents

Recently Viewed

This feature requires Javascript to be enabled.
 

Java3028: Clipping Images

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

Summary: Learn how to use shapes to clip images during the drawing process.

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 use shapes to clip images during the drawing process.

Program specifications

Write a program named Prob04 that uses the class definition shown in Listing 1 and Ericson's media library along with the image file named Prob04a.jpg (see Image 1 ) to produce the graphic output images shown in Image 2 and Image 3 . Don't forget to display your name in the output image as shown.

Figure 1: Image 1: Input file named Prob04a.jpg.
Image 1: Input file named Prob04a.jpg.
Image of a beach scene
Figure 2: Image 2: First output image.
Image 2: First output image.
First output image
Figure 3: Image 3: Second output image.
Image 3: Second output image.
Second output image shows the first output image clipped by an ellipse.

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 Prob04 shown in Listing 1 .

Rotate, mirror, and clip

The program rotates a Picture object by 35 degrees with no scaling. Then it does a four-way mirror on the rotated picture. Finally, it clips the image to an elliptical format as shown in Image 3 .

Required output text

In addition to the two output images shown above, your program must display your name and the other line of text shown in Image 4 .

Figure 4: Image 4: Required text output.
Image 4: Required text output.
Display your name here.
Picture, filename None height 404 width 425

Discussion and sample code

Will discuss in fragments

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

The driver class named Prob04

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

Figure 5: Listing 1: The driver class named Prob04.
Listing 1: The driver class named Prob04.
public class Prob04{
  public static void main(String[] args){
    new Prob04Runner().run();
  }//end main method
}//end class Prob04

If you have been studying the earlier modules in this collection, no explanation of Listing 1 should be required.

Beginning of the class named Prob04Runner

The class named Prob04Runner begins in Listing 2 .

Figure 6: Listing 2: Beginning of the class named Prob04Runner.
Listing 2: Beginning of the class named Prob04Runner.
class Prob04Runner{

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

  public void run(){
    Picture pix = new Picture("Prob04a.jpg");

    //Rotate and mirror the picture.
    pix = rotatePicture(pix,35);
    pix = mirrorUpperQuads(pix);
    pix = mirrorHoriz(pix);

    pix.explore();

Nothing new here

There is nothing new in Listing 2 .

After instantiating a new Picture object from the given image file, Listing 2 calls three methods to rotate, mirror, and display the picture, producing the graphic output shown in Image 2 .

All of the code to accomplish this is essentially the same as code that I have explained in earlier modules.

Clip the picture and display your name

Then Listing 3 calls the clipToEllipse method to clip the picture to an ellipse on a red background as shown in Image 3 . The clipToEllipse method is new to this module, so I will explain it shortly.

Figure 7: Listing 3: Clip the picture and display your name.
Listing 3: Clip the picture and display your name.
    pix = clipToEllipse(pix);

    //Add your name and display the output picture.
    pix.addMessage("Display your name here.",10,20);
    pix.explore();

    System.out.println(pix);
  }//end run

The remaining code in Listing 3 is a repeat of code that I have explained in earlier modules, so I won't have anything further to say about it.

The method named clipToEllipse

The method named clipToEllipse is shown in its entirety in Listing 4 .

Figure 8: Listing 4: The method named clipToEllipse.
Listing 4: The method named clipToEllipse.
  private Picture clipToEllipse(Picture pix){
    Picture result = 
              new Picture(pix.getWidth(),pix.getHeight());
    result.setAllPixelsToAColor(Color.RED);

    //Get the graphics2D object
    Graphics2D g2 = (Graphics2D)(result.getGraphics());

    //Create an ellipse for clipping
    Ellipse2D.Double ellipse =
      new Ellipse2D.Double(28,64,366,275);

    //Use the ellipse for clipping
    g2.setClip(ellipse);

    //Draw the image
    g2.drawImage(pix.getImage(),0,0,pix.getWidth(),
                                pix.getHeight(),
                                null);

    return result;
  }//end clipToEllipse

Behavior of the clipToEllipse method

The clipToEllipse method receives an incoming parameter that is a reference to an object of the Picture class. Basically, here is what the method does:

  • Instantiate a Picture object with an all white background that is the same size as the incoming Picture object.
  • Call Ericson's setAllPixelsToAColor method to convert the white background into a red background.
  • Call Ericson's getGraphics method to get the Graphics object encapsulated in the red Picture object.
  • Cast the Graphics object's reference to type Graphics2D .
  • Construct a new Ellipse2D.Double object with the position, width, and height specified by the constructor parameters.
  • Call Sun's setClip method to set the clipping area on the red Picture object to match the position and shape of the ellipse.
  • Call Ericson's getImage method to get the Image object encapsulated in the incoming Picture object.
  • Call Sun's drawImage method to draw that portion of the incoming picture that fits inside the ellipse on the red Picture object.

The new code

The only code in Listing 4 that is new to this module is the call to the setClip method.

The setClip method is defined in the Graphics class and inherited into the Graphics2D class.

(Among other things, that means that it wasn't necessary for me to cast the Graphics object to type Graphics2D in Listing 4 .)

The setClip method

There are a couple of overloaded versions of the setClip method. The one used in Listing 4 requires an incoming parameter of the interface type Shape .

The Shape interface

Briefly, Sun tells us that the Shape interface "provides definitions for objects that represent some form of geometric shape."

There are several dozen classes that implement the Shape interface, one of which is the class named Ellipse2D.Double . Therefore, the object of that type that is instantiated in Listing 4 satisfies the type requirement for being passed to the setClip method.

Behavior of the setClip method

With regard to the behavior of the setClip method, Sun tells us that the method

"Sets the current clipping area to an arbitrary clip shape."

What is the significance of the clipping area?

The closest answer that I can find for that question is the following statement in Sun's description of the Graphics class:

"All rendering operations modify only pixels which lie within the area bounded by the current clip, which is specified by a Shape in user space and is controlled by the program using the Graphics object."

In other words...

The clipping area is analogous to the current clip . In this case, the position and shape of the current clip is the position and shape of the ellipse.

When the image is later drawn on the red Picture object, only those pixels within the ellipse are modified to show the image. The remaining pixels retain their original color, which was set to red early in Listing 4 .

End of discussion

That concludes my explanation of this program. You will find the methods that I didn't discuss in Listing 5 near the end of the module.

Run the program

I encourage you to copy the code from Listing 5 . 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 Prob04a.jpg to download the required input image file.

Summary

In this module, you learned how to use shapes to clip images during the drawing process.

What's next?

In the next module, you will learn how to merge pictures.

Online video link

Select the following link to view an online video lecture on the material in this module.

Miscellaneous

This section contains a variety of miscellaneous information.

Note:

Housekeeping material
  • Module name: Java OOP: Clipping Images
  • File: Java3028.htm
  • Published: 08/06/12
  • Revised: 02/18/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 provided in Listing 5 below.

Figure 9: Listing 5: Complete program listing.
Listing 5: Complete program listing.
/*File Prob04 Copyright 2008 R.G.Baldwin
*********************************************************/
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.Graphics;
import java.awt.geom.Ellipse2D;
import java.awt.Color;

public class Prob04{
  public static void main(String[] args){
    new Prob04Runner().run();
  }//end main method
}//end class Prob04
//======================================================//

class Prob04Runner{
  public Prob04Runner(){
    System.out.println("Display your name here.");
  }//end constructor
  //----------------------------------------------------//
  public void run(){
    Picture pix = new Picture("Prob04a.jpg");

    //Rotate and mirror the picture.
    pix = rotatePicture(pix,35);
    pix = mirrorUpperQuads(pix);
    pix = mirrorHoriz(pix);

    pix.explore();

    //Clip the picture to an ellipse on a red background.
    pix = clipToEllipse(pix);

    //Add your name and display the output picture.
    pix.addMessage("Display your name here.",10,20);
    pix.explore();

    System.out.println(pix);
  }//end run
  //----------------------------------------------------//

  private Picture clipToEllipse(Picture pix){
    Picture result = 
             new Picture(pix.getWidth(),pix.getHeight());
    result.setAllPixelsToAColor(Color.RED);

    //Get the graphics2D object
    Graphics2D g2 = (Graphics2D)(result.getGraphics());

    //Create an ellipse for clipping
    Ellipse2D.Double ellipse =
      new Ellipse2D.Double(28,64,366,275);

    //Use the ellipse for clipping
    g2.setClip(ellipse);

    //Draw the image
    g2.drawImage(pix.getImage(),0,0,pix.getWidth(),
                                pix.getHeight(),
                                null);

    return result;
  }//end clipToEllipse
  //----------------------------------------------------//
  
  private Picture rotatePicture(Picture pix,
                                double angle){

    //Set up the rotation transform
    AffineTransform rotateTransform =
                                    new AffineTransform();
    rotateTransform.rotate(Math.toRadians(angle),
                           pix.getWidth()/2,
                           pix.getHeight()/2);

    //Get the required dimensions of a rectangle that will
    // contain the rotated image.
    Rectangle2D rectangle2D =
           pix.getTransformEnclosingRect(rotateTransform);
    int resultWidth = (int)(rectangle2D.getWidth());
    int resultHeight = (int)(rectangle2D.getHeight());

    //Set up the translation transform that will translate
    // the rotated image to the center of the new Picture
    // object.
    AffineTransform translateTransform =
                                    new AffineTransform();
    translateTransform.translate(
                      (resultWidth - pix.getWidth())/2,
                      (resultHeight - pix.getHeight())/2);

    //Concatenate the two transforms so that the image
    // will first be rotated around its center and then
    // translated to the center of the new Picture object.
    translateTransform.concatenate(rotateTransform);
    //Create a new Picture object to contain the results
    // of the transformation.
    Picture result = new Picture(
                              resultWidth,resultHeight);

    //Get the graphics context of the new Picture object,
    // apply the transform to the incoming picture and
    // draw the transformed picture on the new Picture
    // object.
    Graphics2D g2 = (Graphics2D)result.getGraphics();
    g2.drawImage(pix.getImage(),translateTransform,null);

    return result;
  }//end rotatePicture
  //----------------------------------------------------//

  //This method mirrors the upper-left quadrant of a
  // picture into the upper-right quadrant.
  private Picture mirrorUpperQuads(Picture pix){
    Pixel leftPixel = null;
    Pixel rightPixel = null;
    int midpoint = pix.getWidth()/2;
    int width = pix.getWidth();
    for(int row = 0;row < pix.getHeight()/2;row++){
      for(int col = 0;col < midpoint;col++){
        leftPixel = pix.getPixel(col,row);
        rightPixel =
                   pix.getPixel(width-1-col,row);
        rightPixel.setColor(leftPixel.getColor());
      }//end inner loop
    }//end outer loop

    return pix;
  }//end mirrorUpperQuads
  //----------------------------------------------------//

  //This method mirrors the top half of a picture into
  // the bottom half.
  private Picture mirrorHoriz(Picture pix){
    Pixel topPixel = null;
    Pixel bottomPixel = null;
    int midpoint = pix.getHeight()/2;
    int height = pix.getHeight();
    for(int col = 0;col < pix.getWidth();col++){
      for(int row = 0;row < midpoint;row++){
        topPixel = pix.getPixel(col,row);
        bottomPixel =
                   pix.getPixel(col,height-1-row);
        bottomPixel.setColor(topPixel.getColor());
      }//end inner loop
    }//end outer loop

    return pix;
  }//end mirrorHoriz
  //----------------------------------------------------//

}//end class Prob04Runner

-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 | 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