Web Development

  Homes arrow Web Development arrow Beginning Java 2 - JDK 1.3 Version Part 2 - O...
 Webmaster Tools
Base64 Encoding 
Browser Settings 
CSS Coder 
CSS Navigation Menu 
Datetime Converter 
DHTML Tooltip 
Dig Utility 
DNS Utility 
Dropdown Menu 
Fetch Content 
Fetch Header 
Floating Layer 
htaccess Generator 
HTML Encoder 
HTML Entities 
IP Convert 
Meta Tags 
Password Encryption
Password Strength
Pattern Extractor 
Ping Utility 
Pop-Up Window 
Regex Extractor 
Regex Match 
Scrollbar Color 
Source Viewer 
Syntax Highlighting 
URL Encoding 
Web Safe Colors 
Forums Sitemap 
Weekly Newsletter
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Contact Us 
Site Map 
Privacy Policy 
  >>> SIGN UP!  
  Lost Password? 

Beginning Java 2 - JDK 1.3 Version Part 2 - Obtaining an Image
By: Developer Shed
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating:  stars stars stars stars stars / 0

    Table of Contents:

    Rate this Article: Poor Best 
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article




    Beginning Java 2 - JDK 1.3 Version Part 2 - Obtaining an Image
    by Wrox Books

    We only considered one ImageIcon constructor when we read icons for our toolbars buttons from a file. That constructor happened to accept a String argument that specified the file name. There are a number of other ImageIcon constructors, so here's the complete set:

    An ImageIcon object contains a reference to an object of type Image as a member. The Image class is an abstract class that is a superclass of all classes that represent images in Java, so a reference of type Image can refer to any instance of a graphical image being used. You can obtain a reference to the Image member of an ImageIcon object by calling its getImage() method. An object of type Image can be created from data in GIF (Graphics Interchange Format), PNG (Portable Network Graphics), or JPEG (Joint Photographic Experts Group) format. So, whether the image data is passed to the constructor as an array - as is the case for two of the ImageIcon constructors, or is obtained from an external source such as a file or a URL object, it must be a GIF, PNG, or JPEG representation of an image.

    While the GIF format for images is very common, it has some limitations. A GIF image can contain a maximum of 256 different colors, albeit selected from a palette of 16 million colors. The JPEG image format has been designed to store photographs, and is a much more sophisticated way of representing a color image. The sophistication comes at a price though. The complexity of the format and the data compression technique used means that it takes much longer to process than a GIF image, but it does make it feasible to transmit good quality photographic images over the net. The JPEG compression technique is also 'lossy', so the quality is not as good as the original image. The PNG image format is also much more flexible than GIF images and it stores images in a lossless form. It is designed to be a portable image storage form for computer-originated images. You can represent grayscale, indexed-color and true color images in PNG format, and you can also include an alpha channel that determines the transparency of the image when it is combined with others.

    The constructors that create the ImageIcon object by referencing a String object specifying a file name, or by referencing a URL object defining an Internet source, always construct the internal Image object before returning. When you specify a URL as the source of the image data, there can be a considerable delay before the ImageIcon object creation is completed, depending on how long it takes to retrieve the image data from the source. Being able to create an ImageIcon object from a URL object is particularly relevant to applets. You can retrieve any images, or indeed any other external data that you use in your applet from an Internet source. Since URLs are so important, let's take a brief detour into how URLs and the URL class work.

    Identifying Sources on a Network

    Data sources on a network are identified by a Uniform Resource Locator, or URL. A source identified by a URL can be a file, or can be some other facility that makes data available, such as a search engine for instance. A URL is a relatively straightforward extension of the normal way of identifying a data source file by the path. It just has some extra bits to identify the computer that contains the source, and how you should communicate with the computer to get at the file. A URL is made up of four pieces of information, some of which may be omitted entirely or take default values:

    The protocol identifies the particular communications method that is to be used to get at the file. HTTP is the HyperText Transfer Protocol used on the World Wide Web, FTP is the File Transfer Protocol, and there are others (we'll see one in the next chapter).

    The domain name identifies the data source uniquely. The last part of the name identifies the kind of organization that owns the computer. For instance, a domain name ending in .com is usually a commercial organization in the USA such as Wrox Press or Sun, .co.uk is a UK company, .edu is an educational establishment in the USA, .ac.uk is an academic or research organization in the UK and .gov is a government or other public body. These are just a few examples. There are lots of others.

    A port is just a number identifying a particular service on a computer. A computer can have many ports - each providing a different service. You don't usually need to specify the port number in a URL because a standard port number, which is typically associated with a particular protocol, will be assigned by default. The port number for the http protocol is 80 for example, and the port number for ftp is 21.

    Because the domain name is part of the reference to a data source, every data source in a network has a unique URL. As long as you know the URL for the source of the data you want on the Internet, and the machine containing it is connected and active, you can go straight to it. Assuming, of course, you have permission!

    The URL Class

    As you saw when we discussed ImageIcon constructors, the URL class encapsulates URLs. This class is defined in the java.net package, so you will need an import statement for the package or for the class when you refer to the URL class in your code. A URL object identifies a particular URL and provides you with the tools to access it and read it, wherever it is on the network. You can create a URL object from a string specifying the URL, for example:

    URL sourceURL = new URL("http://www.wrox.com/");

    This defines a URL object corresponding to the home (or default) page on the Wrox web site.

    Perhaps the most commonly used URL constructor accepts two arguments - a URL object identifying an Internet source, plus a String argument which is a specification for a source within the context of the URL specified by the first argument. The popularity of this form is due to the definition within the Applet class of a method, getCodeBase(), which returns the URL for the source where the .class file for the applet is stored. This enables you to create the URL for a file, picture.gif say, which is stored in the same directory as the applet code, wherever it is, with a statement such as:

    URL getThePicture = new URL(getCodeBase(), "picture.gif");

    There is another method in the Applet class (and therefore inherited in the JApplet class) that provides a useful URL object. This is the getDocumentBase() method that returns a URL object corresponding to the URL for the document (the .html file in other words) that contains the applets. This may well be different from the location of the applet itself. You could call this method to obtain the URL like this:

    URL doc = getDocumentBase();           
    // Get the document containing the applet

    You can also define a URL object by supplying a constructor with separate values for the protocol, the host name, the port number and the source name. You specify the port number as type int, and the other arguments as type String. The web site defined by the domain name "www.ncsa.uiuc.edu" contains a page that explains what a URL is. The file path and name for the page is "/demoweb/url-primer.html". You could define a URL object for this page with the statement:

    URL sourceURL = new URL("http",                         // Protocol
    "www.ncsa.uiuc.edu",            // Host name
    "/demoweb/url-primer.html");    // File

    This uses the default port number for the protocol. You just need to supply the protocol, the domain name and the file path as String objects. Note that URL paths are always specified using forward slashes as separators, regardless of the type of server hosting the data source.

    There is an alternative constructor defined in the URL class:

    URL sourceURL = new URL("http",                         // Protocol
    "www.ncsa.uiuc.edu",            // Host name
    80,                             // Port number
    "/demoweb/url-primer.html");    // File

    The value of 80 for the port number is the standard port number for http. The value of -1 for the port name selects the default port number for the protocol. If you specify a protocol that cannot be identified, a MalformedURLException will be thrown.

    Once you have a URL object, you can get the components of the URL by calling the getProtocol(), getHost(), getPort() and getFile() methods for the object. The getPort() method returns the port number as type int, and the other methods return objects of type String.

    The URL class also implements an equals() method that you can use to compare two URL objects. The expression URL1.equals(URL2) will return true if URL1 and URL2 specify the same file on the same host via the same port number and using the same protocol.

    Perhaps the most useful method in the URL class is the openStream() method. This returns an object of type InputStream, which you can use to read the file represented by the URL. We can try this out by reading the file referenced by the sourceURL object we created in the code fragment above.

    Try It Out - Reading a URL

    This The following example assumes you have a live connection to the Internet. So when the program closes, the connection may still be open, in which case you will need to close it manually. Here's the program to read a URL:

    The program assumes that the directory JunkData that we used in Chapter 8 is still on your C: drive. If it isn't, you can add it, or better still, add the code to check that the directory is there, and if it isn't, create it.

    import java.net.*;
    import java.io.*;
    class ReadURL 
    public static void main(String[] args)
    // Define a URL
    URL sourceURL = new URL(
    // Get a character input stream for the URL
    BufferedReader in = new BufferedReader(
    new InputStreamReader(
    // Create the stream for the output file
    PrintWriter out = new PrintWriter( 
    new BufferedWriter(
    new FileWriter(
    new File("C:/JunkData/netdata.html"))));
    System.out.println("Reading the file " + sourceURL.getFile() +
    " on the host " + sourceURL.getHost() +
    " using " + sourceURL.getProtocol());
    // Read  the URL and write it to a file
    String buffer;                          // Buffer to store lines
    in.close();                             // Close the input stream
    out.close();                            // Close the output file
    catch(MalformedURLException e)
    System.out.println("Failed to create URL:\n" + e);
    catch(IOException e)
    System.out.println("File error:\n" + e);

    While we have used a URL that references a source on the Internet, you could also use a URL to specify a file on your local machine. Executing this as written produces the output:

    Reading the file /demoweb/
    url-primer.html on the host www.ncsa.uiuc.edu using http

    It will also write the text contents of the URL to the file netdata.html. Have a look at what you’ve captured. It’s a good read.

    How It Works

    The object sourceURL is created directly from the URL string. Because the constructor can throw a MalformedURLException - if you type the URL string incorrectly, for example - we have a catch block for this exception following the try block. Note that this exception is derived from IOException so the catch block for this must precede the catch block for IOException. Depending on whether your dial-up-networking is working properly, another typical exception can be java.net.UnknownHostException.

    By calling the openStream() method for the URL object, we obtain a stream that we can pass to the InputStreamReader constructor. A character reader will automatically take care of converting characters from the stream to Unicode. From the InputStreamReader we create a BufferedReader object so input from the stream will be buffered in memory.

    The file is a sizable .html file, so rather than writing it to the screen, we write it to a file in the JunkData directory that we used in Chapter 8. You will then be able to view the file using your web browser. Once we have the BufferedReader object for the URL, the reading of the URL and writing the local file follows the sort of process you have already seen in Chapter 8. We just use the readLine() method to read a line at a time from the URL into the string buffer, and we use the println() method to transfer the buffer contents to the local file. You can now read more about URLs by reading the file contents at your leisure. In the meantime, let's get back to images.

    Displaying an Image

    You display an image in essentially the same way as you display anything else - by calling a method for a Graphics or Graphics2D object. The drawImage() method will draw an image in a graphics context, so from this you can immediately deduce that you can draw images on any components you like. Let's go straight away to trying this out in a working example using an ImageIcon object in the first instance.

    Try It Out - Displaying an Image

    We will implement an applet that creates an ImageIcon from a file in the same directory as the applet's .class file. The code here will refer to an image file wrox_logo.gif. If you want to use this file, you can download it from the Wrox web site. Alternatively you can use your own .gif or .jpg file. Here's the code for the applet:

    import java.awt.*;
    import javax.swing.*;
    import java.net.*;
    public class DisplayImage extends JApplet
    public void init()
    ImageIcon icon = null;
    icon = new ImageIcon(new URL(getCodeBase(),
    catch(MalformedURLException e)
    System.out.println("Failed to create URL:\n" + e);
    int imageWidth = icon.getIconWidth();           // Get icon width
    int imageHeight = icon.getIconHeight();         // and its height
    // Set applet size to fit the image
    // Create panel a showing the image
    ImagePanel imagePanel = new ImagePanel(icon.getImage());
    // Add the panel to the content pane
    // Class representing a panel displaying an image
    class ImagePanel extends JPanel
    public ImagePanel(Image image)
    this.image = image;
    public void paint(Graphics g)
    g.drawImage(image, 0, 0, this);                        
    // Display the image
    Image image;                                             
    // The image

    You will need an HTML file to run the applet. You could call it DisplayImage.html, and make the contents:

    <applet code="DisplayImage.class" width=50 height=50></applet>

    This just sets the width and height parameters for the applet to arbitrary values. The applet will resize itself to accommodate the image. When I ran this with appletviewer, it displayed the window below. (Although you may prefer to refer back to Chapter 1, which explains how to run the applet in a browser using the plug-in.)

    How It Works

    We retrieve the icon from the file wrox_logo.gif in the Images directory relative to the URL that holds the code for the applet. The URL class constructor can throw an exception, so we must arrange to catch exceptions of type MalformedURLException here in order to get the code to compile. The ImageIcon class constructor does everything necessary to obtain the data from the file, and uses it to create the image. The constructor will only return when this has been completed.

    The getIconWidth() and getIconHeight() methods for the ImageIcon object return the width and height of the image respectively, and we use these as arguments to the resize() method for the JApplet object, to adjust the size of the applet to accommodate the image.

    We have to remember that an applet based on the JApplet class is similar to a window based on the JFrame class in that anything we want to display in an applet must be added to the content pane for the applet object. For this reason we define an inner class, ImagePanel, that will draw the image for the ImageIcon object, and we can add an object of this class to the content pane for the applet. The ImagePanel class is quite simple. The constructor saves the reference to the Image object that is passed to it in a data member of the class, and the paint() method calls drawImage() to display the image.

    Note that no cast to Graphics2D is necessary in the paint() method since the drawImage() method that we are using is defined in the Graphics class. There are several other overloaded versions of this method, including two that are defined in the Graphics2D class, so when you want to use these, a cast will be necessary. The arguments to the version of drawImage() that we use here are:

    • A reference to the Image object to be drawn
    • The coordinates of the position where the image is to be drawn
    • A reference to an ImageObserver object

    An image is defined by its top-left corner point, so in our applet we place the top-left corner of the image at the origin of the user coordinate system for our panel. An ImageObserver object is an object of a class that implements the ImageObserver interface, and since the Component class implements this interface, any component, including objects of our inner class ImagePanel, are ImageObserver objects. The ImageObserver interface handles the process of accessing image data from Internet sources where there may be a considerable time delay in loading the image. This interface provides the means to allow you to determine whether an image has been loaded or not, and we will come back to this a little later in this chapter.

    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

    More Web Development Articles
    More By Developer Shed



    - On Page SEO for New Domains
    - Improve Your Site`s Speed
    - Safari Books Online Review
    - Creating an Estore From the Ground Up
    - Most Common SEO Mistakes Developers Make
    - Making the Most of Your Titles and Meta Desc...
    - Five Ways Using Flash Can Damage Your Site
    - A Web Designer`s Guide to Colors
    - Use Webstarts to Create a Free Site
    - More Than Just Looks. How Your Web Design C...
    - How to Design Content Pages
    - Mint Review
    - Make Your WordPress Website Look Professional
    - How to Create a Mobile Web Site
    - Meta Tags: Still Useful?

    Developer Shed Affiliates


    © 2003-2018 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap