Class Image in AWT in Java:

Please read this article on Image basics here. The abstract class Image is the superclass of all classes that represent graphical images. With Image class, we can load an image object that obtains its pixel data from a specified URL.

Image abstract class represents a displayable image in a platform-independent way. An Image object may not be instantiated directly through a constructor, it must be obtained through a call like Applet.getImage() or Component.createImage().getSource() method returns the ImageProducer object that produces the image data.

getGraphics() returns a Graphics object that can be used for drawing into offscreen images (but not images that offscreen are downloaded or generated by an ImageProducer).

The Image class represents a displayable object maintained in memory. Because Image is an abstract class, we never work with the Image class itself, but with a platform-specific subclass. However, we should never need to know what that subclass is. To draw on an Image, get its graphics context.

Image is an abstract class implemented by many different platform-specific classes. The system that runs our program will provide an appropriate implementation; we do not need to know anything about the platform-specific classes, because the Image class completely defines the API for working with images. If we just want to know, the platform-specific packages used by the JDK are:

  • sun.awt.win32.Win32Image on Java 1.0 Windows NT/95 platforms
  • sun.awt.windows.WImage on Java 1.1 Windows NT/95 platforms
  • sun.awt.motif.X11Image on UNIX/Motif platforms
  • sun.awt.macos.MacImage on the Macintosh

The structure of the class is given below:

public abstract class java.awt.Image extends java.lang.Object implements java.io.Serializable{
//member element:
public static final int SCALE_AREA_AVERAGING;
public static final int SCAL_DEFAULT;
public static final int SCALE_FAST;
public static final int SCALE_REPLICATE;
public static final int SCALE_SMOOTH;
public final static Object UndefinedProperty;
//The UndefinedProperty Object should be returned whenever a property which was defined for a particular
//image is fetched.
//constructor
public Image();//default constructor
//Methods:
public abstract void flush();
public abstract Graphics getGraphics();
public abstract int getHeight(ImageObserver observer);
public abstract Object getProperty(String name,ImageObserver observer);
public abstract ImageProducer getSource();
public abstract int getWidth(ImageObserver observer);
public Image getScaledInstance(int width, int height, int hints);
} 

The details of the class structure are given as follows:

public final static int SCALE_AREA_AVERAGING;

public final static int SCALE_AREA_AVERAGING represents a flag that requests use of AreaAveragingScaleFilter or a reasonable alternative provided by the toolkit..

public final static int SCALE_DEFAULT;

public final static int SCALE_DEFAULT represents a flag that requests use of the default image scaling algorithm.

public final static int SCALE_FAST;

public final static int SCALE_FAST represents a flag that requests use of an image scaling algorithm that is faster rather than smoother.

public final static int SCALE_REPLICATE;

public final static int SCALE_REPLICATE represents a flag that requests use of ReplicateScaleFilter or a reasonable alternative provided by the toolkit..

public final static int SCALE_SMOOTH;

public final static int SCALE_SMOOTH represents a flag that requests the use of an image scaling algorithm that is smoother rather than faster.

public final static Object UndefinedProperty;

public final static Object UndefinedProperty returns object from getProperty() to indicate that the requested property is unavailable. However, the latest java versions introduced the getScaledInstance() method. The final parameter to the method is a set of hints to
tell the method how best to scale the image.

public abstract void flush();

public abstract void flush() method resets the image to the initial state. Lets assume that acquire an image over the network with getImage(). The first time we display the image, it will be loaded over the network. If we redisplay the image, AWT normally reuses the original image.

However, if we call flush() before redisplaying the image, AWT fetches the image again from its source. (Images created with createImage() aren’t affected.)

The flush() method is useful if we expect images to change while our program is running. The following program demonstrates flush(). It reloads and displays the file flush.gif every time we click the mouse. If we change the file flush.gif and click on the mouse, we will see the new file.

How to use flush() method in java?

The below code will display how to use flush: Here the image is drawn first and when the mouse is clicked, it is flushed and redrawn.

package testPackage;
import java.awt.Event;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
public class TestFlush extends Frame {
	Image img;
	TestFlush(){
		super("started flushing process");
		img=Toolkit.getDefaultToolkit().getImage("C:\\Blog Related\\java-base.png");
		resize(400,400);
	}
	public void paint(Graphics g) {
		g.drawImage(img, 0, 0, 400, 400, this);
		}
	public boolean mouseDown(Event e,int x,int y) {
		img.flush();
		repaint();
		return true;
	}
	public static void main(String[] args) {
		Frame myFrame=new TestFlush();
		myFrame.show();
	}

The output of the code :

How to use flush method
How to use flush method
public abstract Graphics getGraphics();

public abstract Graphics getGraphics() method gets the graphics context of the image for drawing. The method getGraphics() works only for Image objects created in memory with Component.createImage (int, int). If the image came from a URL or a file (i.e., from getImage()), getGraphics() throws the run-time exception ClassCastException.

This method returns the graphics context of the image.

public abstract int getHeight(ImageObserver observer);

public abstract int getHeight(ImageObserver observer) method returns image height, or -1 if the height is not yet available. An image’s size is available long before loading is complete, so it is often useful to call getHeight() while the image is loading.

This method returns image height, or -1 if the height is not yet available.

Parameter
observer – An image observer; usually the Component on which the image is rendered.

public abstract Object getProperty (String name, ImageObserver observer);

public abstract Object getProperty (String name, ImageObserver observer) method retrieves a property from the image’s private property list. An object representing the requested property name will be returned for observer. observer represents the Component on which the image is rendered.

If the property name exists but is not available yet, getProperty() returns null. If the property name does not exist, the getProperty() method returns the Image.UndefinedProperty object.

Each image type has its property list. A property named comment stores a comment String from the image’s creator. The CropImageFilter adds a property named correct. If we ask getProperty() for an image’s correct property, we get a Rectangle that shows how the
the original image was cropped.

This method returns the Object representing the requested property, null, or undefined property.

Parameter
name – Name of the property to fetch.
observer – An image observer; usually the Component on which the image is rendered.

public Image getScaledInstance(int width, int height, int hints);

public Image getScaledInstance(int width, int height, int hints) method creates a copy of an image, scaled to width x height and using an algorithm chosen based on the hints given. It enables us to generate scaled versions of images before they are needed.

In the initial days of Java, it was necessary to tell the drawImage() method to do the scaling. However, this meant that scaling didn’t take place until we actually tried to draw the image. Since scaling takes time, drawing the image required more time; the net result was degraded appearance.

With Java’s latest versions, we can generate scaled copies of images before drawing them; then we can use a version of drawImage() that does not do scaling, and therefore is much quicker.

The width parameter of getScaledInstance() is the new width of the image. The height
parameter is the new height of the image. If either is -1, the scaling retains the aspect ratio of the original image.

For instance, if the original image size was 300 by 72 pixels, and width and height were 100 and -1, the new image size would be 100 by 29 pixels. If both width and height are -1, the getScaledInstance() method retains the image’s original size. The hints parameter is one of the Image class constants.

Image i = getImage (getDocumentBase(), "test.jpg");
Image j = i.getScaledInstance (100, -1, Image.SCALE_FAST);

This method returns the scaled image. It may be loaded asynchronously, even if the original image was fully loaded.

Parameter
width – The width for the scaled image. Use -1 to preserve the aspect ratio with reference to height.
height – The height for the scaled image. Use -1 to preserve the aspect ratio with reference to width.
hints – One or more of the SCALE_ constants.

public abstract ImageProducer getSource();

public abstract ImageProducer getSource() method returns the ImageProducer of the image. This object represents the image’s source. Once we have the ImageProducer, we can use it to do additional image processing;

for example, we can create a modified version of the original image by using a FilteredImageSource.

This method returns the ImageProducer of the image.

public abstract int getWidth(ImageObserver observer);

public abstract int getWidth(ImageObserver observer) method returns Image width, or -1 if the width is not yet available. An image’s size is available long before loading is complete, so it is often useful to call getWidth() while the image is loading.

This method returns Image width, or -1 if the width is not yet available.

Parameter
observer – An image observer; usually the Component on which the image is rendered.

Applet class has the following methods to work with images:

public image getImage(URL url);//returns an image object given an URL
public image getImage(URL url,String name);//Returns an image object with the URL and the name specified. 

How to create animation of images using gra

The below code will depict how to create an animation

package testPackage;

import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;

public class MyAnimation extends Frame{
	static Image img[];
	static int imageCount=100;
	static int counter=0;
	MyAnimation()
	{
		super("My Animation");
	}
	public static void main(String[] args) {
		Frame myFrame=new MyAnimation();
		myFrame.resize(400,400);
		myFrame.show();
		img=new Image[imageCount];
		for(int j=0;j<imageCount;j++)
			img[j]=Toolkit.getDefaultToolkit().getImage("C:\\Blog Related\\java-base"+j+".png");
		
	}
	public synchronized void paint(Graphics g) {
		g.translate(insets().left, insets().top);
		g.drawImage(img[counter],0,0,this);
		counter=counter+1;
		if(counter==imageCount)
			counter=0;
		repaint(400);
	}

}

This program displays images with the name java-base.png, where imageCount is a number between 0 and 99. It fetches the images using the getImage() method of the Toolkit class–hence, the call to Toolkit.getDefaultToolkit(), which gets a Toolkit object to work with. The paint() method displays the images in sequence, using drawImage(). paint() ends with a call to repaint(400), which schedules another call to paint() in 400 milliseconds.

What is Double buffering in Java in the context of Image?

Twofold or double buffering means drawing to an offscreen context setting and afterward showing this design or graphics setting to the screen in a solitary activity. Up until this point, we have done all our drawing legitimately on the screen- – that is, to the graphics setting gave by the paint() strategy.

As our projects develop progressively mind boggling and complex, paint() gets greater and greater, and it takes additional time and assets to refresh the whole drawing zone.

On a moderate machine, the client will see the individual drawing tasks happen, which will make our program look moderate and inconvenient. By utilizing the twofold or double buffering strategy, we can take as much time as necessary drawing to another graphics setting that isn’t shown.

At the point when we are prepared, we advise the framework to show a totally new picture without a moment’s delay. Doing so dispenses with the plausibility of seeing fractional screen(partial screen) refreshes and glimmering(flickering).

The first thing we need to do is create an image as our drawing canvas. To get an image object, call the createImage() method. createImage() is a method of the Component class.When creating an application and extending Frame, createImage() returns null until the Frame’s peer exists.

To make sure that the peer exists, we need yo call addNotify() in the constructor, or make sure we call show() before calling createImage(). Here’s the call to the createImage() method that we’ll use to get an Image object:

Image img = createImage (400, 400); // width and height

Once we have an Image object, we have an area we can draw on. But how do we draw on it? There are no drawing methods associated with Image; they’re all in the Graphics class. So we need to get a Graphics context from the Image. To do so, we need to call the getGraphics() method of the Image class, and we need to use that Graphics context for our drawing:

Graphics buffer = im.getGraphics();

Now we can do all our drawings with buffer. To display the drawing, the paint() method only needs to call drawImage(img, . . .).

The hidden connection between the Graphics object, buffer, and the Image we are creating, img. we draw onto buffer; then we use drawImage() to render the image on the on-screen Graphics context within the paint().

Another feature of buffering is that we do not have to redraw the entire image with each call to paint(). The
buffered image we are working on remains in memory, and we can add to it at will. If we are drawing directly to
the screen, we should have to recreate the entire drawing each time paint() is called; remember, paint()
always hands us a completely new Graphics object.

Don't miss out!
Subscribe To Newsletter

Receive top technical news, lesson ideas, travel tips and more!

Invalid email address
Give it a try. You can unsubscribe at any time.

I am the founder and owner of the blog - TechTravelHub.com, always love to share knowledge on test automation,tools,techniques and tips.I am a passionate coder of Java and VBScript.I also publish articles on Travel ideas and great honeymoon destinations.Apart from these, I am a gear-head,love to drive across India. I have shared lots of articles here on How to travel several parts of India.Customization of cars aka car modification is my another hobby.Get in touch with me on [email protected]

Write A Comment