ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Basic Image Manipulation in Java

Updated on May 9, 2011

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.
  }
}
working

This website uses cookies

As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://corp.maven.io/privacy-policy

Show Details
Necessary
HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
LoginThis is necessary to sign in to the HubPages Service.
Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
AkismetThis is used to detect comment spam. (Privacy Policy)
HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
Features
Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
MavenThis supports the Maven widget and search functionality. (Privacy Policy)
Marketing
Google AdSenseThis is an ad network. (Privacy Policy)
Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
Index ExchangeThis is an ad network. (Privacy Policy)
SovrnThis is an ad network. (Privacy Policy)
Facebook AdsThis is an ad network. (Privacy Policy)
Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
AppNexusThis is an ad network. (Privacy Policy)
OpenxThis is an ad network. (Privacy Policy)
Rubicon ProjectThis is an ad network. (Privacy Policy)
TripleLiftThis is an ad network. (Privacy Policy)
Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
Statistics
Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
ClickscoThis is a data management platform studying reader behavior (Privacy Policy)