Basic Image Manipulation in Java

Basic Image Manipulation in Java

This tutorial illustrates basic image manipulation in Java. We construct a simple Java class that will load a jpeg image from a web site and display it in a frame on the local computer. The code is written as a Java Desktop Application and should scale to other java architecture as well.

Our project consists of two classes:

  1. Main
  2. ImageLoaderDemo

We provide a simple Main class with a static main() method that serves as the entry point for the application. The main( ) method instantiates an instance of the ImageLoaderDemo class and passes the web address of the image to be processed. The Main class can be removed completely without any impact on the functionality of the ImageLoaderDemo class.

The ImageLoaderDemo class inherits from the Java Frame class. In the ImageLoaderDemoconstructor, methods from the Frame are called to create a display a frame. The image is loaded using the awt toolbox with a single call to getImage():

mImage = java.awt.Toolkit.getDefaultToolkit().getImage(url);

This method accepts an object of type URL as the only argument. A URL object is easy to create. We simply pass a web address to the URL constructor. We do that in the main( ) method, line 19:

new ImageLoaderDemo(new URL(url));

The preceding line calls the constructor of the URL class, which returns a reference to the newly created URL object. That URL object reference is immediately passed on to the ImageLoaderDemo constructor. Java garbage collection prevents objects from being deallocated until they are no longer accessible.

Line 120 in the ImageLoaderDemo class finally drops the image onto the frame:

g.drawImage(mImage, insets.left, insets.top, this);  

This line requires a graphics context reference. The graphics context is magically (just kidding) provided by the super class, Frame, and made available in the Paint( ) method in our subclass. We are overriding the default Paint( ) method that our base class would otherwise invoke. Note that nowhere in our code is our Paint( ) method explicitly called.

The ImageLoaderDemo class - there's a left/right scroller at the bottom of the capsule.

/*
 * In this project we introduce the awt toolkit:
 *    http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Toolkit.html
 * 
 * 1. We create a frame.
 * 2. We create and load an image in the frame.
 * 3. Eventually the image gets displayed in the frame by a higher power.
 *
 * 
 * Adapted by: nicomp: http://hubpages.com/profile/nicomp
 * 
 * This gets a bit confusing but the bottom line is that you need a graphics context object
 *   in order to draw stuff. You only get that from the JVM. See the paint() method below.
 */

import java.awt.*;
import java.awt.image.*;
import java.net.URL;

/**
 * Image Loader Demo class
 * <br>We are inheriting the properties and methods of the frame class.
 * <br>Since the frame class is our super class, we will have access to a graphics context object.
 * @author: nicomp http://hubpages.com/profile/nicomp
 */
public class ImageLoaderDemo extends Frame {

//  Here is where we will store our image.
    private Image mImage;
//  We would like to do this with a BufferedImage object, but the awt toolkit can't handle buffered image objects
//  static private BufferedImage mImage

//  We will keep track of how many times the image is repainted.
    int imageUpdateCallCount;

    /**
     *   Constructor
     *   <br>url = the Universal Resource Locator (web address) of the image to load.
     *   <br>It would be nice to add a listener. Using the Task Manager to close the window is a drag.
     */
    public ImageLoaderDemo(URL url) {
        super("Image Loader Demo");   // Call the base class constructor (a Frame object)
        imageUpdateCallCount = 0;

//      Built-in methods to manipulate images, and do other stuff.
//      It's called the "Toolkit" and it's part of the awt package.
//      getImage() can also handle file names on the local network.
        mImage = java.awt.Toolkit.getDefaultToolkit().getImage(url);
        rightSize();
    }

    /**
     *   Adjust the image so it will display properly.
     */
    private void rightSize() {
        int width = mImage.getWidth(this);
        int height = mImage.getHeight(this);
        if (width == -1 || height == -1) {
            return;
        }
//      Look up the border size for this image, if any.
        Insets insets = getInsets();
//      Resize the container to handle the borders.
        setSize(width + insets.left + insets.right, height + insets.top + insets.bottom);
//      Make the frame visible.
        setVisible(true);
    }

    /**
     * A call-back method that is referenced by the base class (Frame)
     *  to configure the image. 
     * Note that this method is not called explicitly in this project.
     * The point is that we would never know this was necessary unless we
     *  studied a working example.
     * @param img
     * @param infoflags
     * @param x
     * @param y
     * @param width
     * @param height
     * @return
     */
    public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) {
//      This gets a little odd: we will see that this method is called quite a few times.
        System.out.println("imageUpdate()" + imageUpdateCallCount++);
        if ((infoflags & ImageObserver.ERROR) != 0) {
            System.out.println("Error loading image!");
            System.exit(-1);
        }
        if ((infoflags & ImageObserver.WIDTH) != 0 && (infoflags & ImageObserver.HEIGHT) != 0) {
            rightSize();
        }
        if ((infoflags & ImageObserver.SOMEBITS) != 0) {
            repaint();  // This triggers a call to paint() (see below)
        }
        if ((infoflags & ImageObserver.ALLBITS) != 0) {
            rightSize();
            repaint();  // This triggers a call to paint() (see below)
            return false;
        }
        return true;
    }

    /**
     * Ditto. See comments for imageUpdate method
     * @param g
     */
//    public void update(Graphics g) {
//        paint(g);
//    }

    /**
     * Called by update() which is called by ... who knows.
     * Whoever calls this will send us a Graphics Context object to draw onto.
     * See comments for imageUpdate method.
     * @param g
     */
    public void paint(Graphics g) {
        Insets insets = getInsets();
        g.drawImage(mImage, insets.left, insets.top, this);
    }
}

The Main class that drives the ImageLoaderDemo class

/*
 * Entry point for test main.
 * 
 */
import java.net.URL;    // Convert a string object to a URL object

/**
 * Entry Point for ImageLoaderDemo class.
 * @author nicomp: http://hubpages.com/profile/nicomp
 */
public class Main {
//  Entry point for the project.
  public static void main(String[] args) throws Exception {
    String url = "http://s1.hubimg.com/u/2305196_177.jpg";
    if (args.length > 0) url = args[0];

//  Instantiate an object of type ImageLoaderDemo.
//  We don't need a handle on it; we just want the constructor of the ImageLoaderDemo class to be called.
    new ImageLoaderDemo(new URL(url));  // The URL constructor is called too.
//  The frame persists when the main ends.
  }
}

More by this Author

  • The Importance of Doing Laundry
    19

    We could nag, but this is better. It is less work for us to use the words of others to emphasize the importance of doing laundry. Besides, if you saw the way we dressed, you'd laugh your mouse off.

  • Data Hiding in Java
    12

    Data Hiding is an aspect of Object Oriented Programming (OOP) that allows developers to protect private data and hide implementation details. In this tutorial we examine basic data hiding techniques in Java.

  • Introduction to Windows Notepad
    5

    A useful text editor is an essential component of any personal computer. Every day we need to make notes, compose documents, and record vital pieces of information. We depend on our text editor. Microsoft provided...


Comments 7 comments

Carol the Writer profile image

Carol the Writer 6 years ago from Houston, Texas

I feel stupider just reading your post. Anyway, I'm sure some people will love this. - Carol


psychicdog.net profile image

psychicdog.net 6 years ago

thanks Nicomp, intriguing reading. I know for a fact a site built using Java so grateful for the lesson. I'm not sure how far Java as a language has caught on or it's special features or even whether it is a preferred language but sounds like image handling is fairly advanced.


nicomp profile image

nicomp 6 years ago from Ohio, USA Author

Thanks!


ballu 6 years ago

hopeless


nicomp profile image

nicomp 6 years ago from Ohio, USA Author

@ballu: Thank you for you comments.


sacheal profile image

sacheal 6 years ago

men,i really enjoyed going through your program.although i'm still a baby programmer, i'm still learning and i really want us to be friends so that i can learn better. this's my mail aghasacheal@yahoo.com thanks


nicomp profile image

nicomp 5 years ago from Ohio, USA Author

I sure wish the code capsule would scroll left and right somewhere else besides all the way at the bottom...

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working