Skip to content Skip to navigation

OpenStax_CNX

You are here: Home » Content » Java3030: Merging Pictures

Navigation

Recently Viewed

This feature requires Javascript to be enabled.
 

Java3030: Merging Pictures

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

Summary: Learn how to merge 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 do a linear merge on two pictures based on the distance of each pixel from the left side of the picture.

Program specifications

Write a program named Prob05 that uses the class definition shown in Listing 1 and Ericson's media library along with the image files named Prob05a.jpg and Prob05b.jpg (see Image 1 and Image 2 ) to produce the graphic output image shown in Image 3 .

1
Image 1: Input file named Prob05a.jpg.
Image of a penguin near the right side of the frame.
2
Image 2: Input file named Prob05b.jpg.
Image of a rabbit near the left side of the frame
3
Image 3: Required graphic output image.
Merged image showing a rabbit near the left side of the the frame and a penguin near the right side of the frame. Image also shows an elliptical sun in the center with a gradient from yellow to orange.

Required output text

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

4
Image 4: Required output text.
Display your name here.
Picture, filename None height 252 width 330

Discussion and sample code

This program does a linear merge on two pictures based on the distance of each pixel from the left side of the picture. The program also adds a sun with a gradient and the student's name to the picture.

Will discuss in fragments

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

The driver class named Prob05

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

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

The code in Listing 1 shouldn't require an explanation at this stage in the course.

Beginning of the class named Prob05Runner

The class named Prob05Runner begins in Listing 2 .

6
Listing 2: Beginning of the class named Prob05Runner.
class Prob05Runner{
  public Prob05Runner(){
    System.out.println("Display your name here.");
  }//end constructor

As with Listing 1 , the code in Listing 2 shouldn't require an explanation.

The run method of the Prob05Runner class

Listing 1 calls the run method on an object of the Prob05Runner class. The run method is shown in its entirety in Listing 3 .

7
Listing 3: The run method of the Prob05Runner class.
  public void run(){
    Picture penguin = new Picture("Prob05a.jpg");
    Picture hare = new Picture("Prob05b.jpg");
    merge(hare,penguin);
    hare = crop(hare,6,58,330,252);
    hare.addMessage("Display your name here.",10,20);
    drawSun(hare);
    hare.show();
    System.out.println(hare);
  }//end run

The only thing in Listing 3 that I haven't explained in earlier modules is the call to the merge method, so I will limit my discussion to that method.

The merge method

The merge method is used to merge the image in Image 1 with the image in Image 2 to produce the image shown in Image 3 .

(Note, however, that the merged image was cropped to eliminate the buttons at the top of F igure 1 and Image 2 before displaying it in Image 3 .)

A linear merge

The merge method does a linear merge on two pictures based on the distance of each pixel from the left side of the picture.

The method assumes that both pictures have the same dimensions.

Beginning of the merge method

The merge method begins in Listing 4 .

8
Listing 4: Beginning of the merge method.
  private void merge(Picture left,Picture right){
    int width = left.getWidth();
    int height = left.getHeight();

    double scaleL = 0;
    double scaleR = 0;
    int redL = 0;
    int greenL = 0;
    int blueL = 0;
    int redR = 0;
    int greenR = 0;
    int blueR = 0;
    Pixel pixelL = null;
    Pixel pixelR = null;

The code in Listing 4 simply declares and initializes a large number of working variables.

Do the merge

The merge is accomplished in the nested for loop in Listing 5 .

9
Listing 5: Do the merge.
    for(int row = 0;row < height;row++){
      for(int col = 0;col < width;col++){
        scaleR = (double)col/width;
        scaleL = 1.0 - scaleR;
        pixelL = left.getPixel(col,row);
        pixelR = right.getPixel(col,row);

        redL = pixelL.getColor().getRed();
        greenL = pixelL.getColor().getGreen();
        blueL = pixelL.getColor().getBlue();

        redR = pixelR.getColor().getRed();
        greenR = pixelR.getColor().getGreen();
        blueR = pixelR.getColor().getBlue();

        redL = (int)(redL*scaleL + redR*scaleR);
        greenL = (int)(greenL*scaleL + greenR*scaleR);
        blueL = (int)(blueL*scaleL + blueR*scaleR);

        pixelL.setColor(new Color(redL,greenL,blueL));
      }//end inner loop
    }//end outer loop
  }//end merge

Difficult to explain

Although the code in Listing 5 is long, tedious, and ugly, it isn't complicated However, it is somewhat difficult to explain in words.

Two scale factors

The body of the for loop begins by computing a pair of scale factors named scaleR and scaleL . The factor named scaleR has a maximum value of 1.0 and is directly proportional to the distance of the current pixel from the left edge of the picture.

The factor named scaleL also has a maximum value of 1.0 and is inversely proportional to the distance of the pixel from the left edge.

Get and save color components

The red, green, and blue values for the same pixel location in each of the pictures are obtained and saved.

Compute a new set of color values

A new set of red, green, and blue color values are computed as the sum of scaled versions of the pixel colors from the rabbit image pixel and the penguin image pixel.

The nature of the scaling

The scaling is such that the pixel colors from the rabbit image contribute most heavily to output pixels to the left of center and pixel colors from the penguin image contribute most heavily to output pixels to the right of center.

You can see the effect of this scaling algorithm in Image 3 .

The pixels in the horizontal center

The pixels along a vertical line at the center of the output image contain equal contributions of colors from both images.

End of discussion

That concludes the explanation of the code in this program.

You can view the drawSun and crop methods in Listing 6 near the end of the module.

Run the program

I encourage you to copy the code from Listing 6 . 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 Prob05a.jpg and Prob05b.jpg to download the required input image files.

Summary

In this module, you learned how to merge two 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: Merging Pictures
  • File: Java3030.htm
  • Published: 08/07/12
  • Revised: 01/01/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 6 below.

10
Listing 6: Complete program listing.
/*File Prob05 Copyright 2008 R.G.Baldwin
*********************************************************/
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Graphics;
import java.awt.GradientPaint;
import java.awt.geom.Ellipse2D;

public class Prob05{
  //DO NOT MODIFY THE CODE IN THIS CLASS DEFINITION.
  public static void main(String[] args){
    new Prob05Runner().run();
  }//end main method
}//end class Prob05
//======================================================//

class Prob05Runner{
  public Prob05Runner(){
    System.out.println("Display your name here.");
  }//end constructor
  //----------------------------------------------------//
  public void run(){
    Picture penguin = new Picture("Prob05a.jpg");
    Picture hare = new Picture("Prob05b.jpg");
    merge(hare,penguin);
    hare = crop(hare,6,58,330,252);
    hare.addMessage("Display your name here.",10,20);
    drawSun(hare);
    hare.show();
    System.out.println(hare);
  }//end run
  //----------------------------------------------------//

  private void drawSun(Picture pic){

    Graphics2D g2d = (Graphics2D)(pic.getGraphics());
    int width = 75;
    int height = 50;
    int center = pic.getWidth()/2;
    int xCoor = center - width/2;
    int yCoor = 75;


    //Create the gradient for painting from yellow to red
    // with yellow at the left of the sun and red at the
    // right.
    GradientPaint gPaint = new GradientPaint(
                              xCoor, yCoor+height/2,
                              Color.YELLOW,
                              xCoor+width,yCoor+height/2,
                              Color.ORANGE);

    //Set the gradient and draw the ellipse
    g2d.setPaint(gPaint);
    g2d.fill(new Ellipse2D.Double(
                               xCoor,yCoor,width,height));

  }//end drawSun
  //----------------------------------------------------//

  //Assumes both pictures have the same dimensions.
  // Does a linear merge on two pictures based on the
  // distance of each pixel from the left side of the
  // picture.
  private void merge(Picture left,Picture right){
    int width = left.getWidth();
    int height = left.getHeight();

    double scaleL = 0;
    double scaleR = 0;
    int redL = 0;
    int greenL = 0;
    int blueL = 0;
    int redR = 0;
    int greenR = 0;
    int blueR = 0;
    Pixel pixelL = null;
    Pixel pixelR = null;

    for(int row = 0;row < height;row++){
      for(int col = 0;col < width;col++){
        scaleR = (double)col/width;
        scaleL = 1.0 - scaleR;
        pixelL = left.getPixel(col,row);
        pixelR = right.getPixel(col,row);

        redL = pixelL.getColor().getRed();
        greenL = pixelL.getColor().getGreen();
        blueL = pixelL.getColor().getBlue();

        redR = pixelR.getColor().getRed();
        greenR = pixelR.getColor().getGreen();
        blueR = pixelR.getColor().getBlue();

        redL = (int)(redL*scaleL + redR*scaleR);
        greenL = (int)(greenL*scaleL + greenR*scaleR);
        blueL = (int)(blueL*scaleL + blueR*scaleR);

        pixelL.setColor(new Color(redL,greenL,blueL));
      }//end inner loop
    }//end outer loop
  }//end merge
  //----------------------------------------------------//

  //Crops a Picture object to the given width and height
  // with the upper-left corner located at startCol and
  // startRow.
  private Picture crop(Picture pic,int startCol,
                                   int startRow,
                                   int width,
                                   int height){
    Picture output = new Picture(width,height);

    int colOut = 0;
    int rowOut = 0;
    int col = 0;
    int row = 0;
    Pixel pixel = null;
    Color color = null;
    for(col = startCol;col < startCol+width;col++){
      for(row = startRow;row < startRow+height;row++){
        color = pic.getPixel(col,row).getColor();
        pixel = output.getPixel(colOut,rowOut);
        pixel.setColor(color);
        rowOut++;
      }//end inner loop
      rowOut = 0;
      colOut++;
    }//end outer loop
    return output;
  }//end crop
}//end class Prob05Runner

-end-

Content actions

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