The Applet
class uses two
getImage()
methods to load images:
public Image getImage(URL
url)
public Image getImage(URL url, String
name)
The Toolkit
class declares two more
getImage()
methods to load images:
public abstract Image getImage(URL
url)
public abstract Image getImage(String
filename)
Toolkit toolkit = Toolkit.getDefaultToolkit(); Image image1 = toolkit.getImage("imageFile.gif"); Image image2 = toolkit.getImage(new URL("http://java.sun.com/graphics.gif"));
With the help of an image producer such as the
MemoryImageSource
class, you can construct
images from scratch:
int w = 100; int h = 100; int[] pix = new int[w * h]; int index = 0; for (int y = 0; y < h; y++) { int red = (y * 255) / (h - 1); for (int x = 0; x < w; x++) { int blue = (x * 255) / (w - 1); pix[index++] = (255 << 24) | (red << 16) | blue; } } Image img = createImage(new MemoryImageSource(w, h, pix, 0, w));
Normal size in the upper left corner of the
Component
area (0, 0):
g.drawImage(image, 0, 0,
this);
Scaled to be 300 pixels wide and 62 pixels tall, starting at the coordinates (90, 0):
g.drawImage(myImage, 90, 0, 300, 62,
this);
![]() | Note |
---|---|
The |
An image producer: It produces raw data for
Image
objects and implements the
ImageProducer
interface.
An image consumer: It is an object interested in data
produced by image producers and implements the
ImageConsumer
interface.
An image consumer: It is an object interested in data
produced by image producers and implements the
ImageConsumer
interface.
Code for a rotation filter:
ImageFilter filter = new RotateFilter(angle); ImageProducer producer = new FilteredImageSource(sourceImage.getSource(), filter); resultImage = createImage(producer); repaint();
Creating an ImageFilter
subclass:
Image filters implement the
ImageConsumer
interface.
void setDimensions(int width, int height); void setProperties(Hashtable props); void setColorModel(ColorModel model); void setHints(int hintflags); void setPixels(int x, int y, int w, int h, ColorModel model, byte pixels[], int off, int scansize); void setPixels(int x, int y, int w, int h, ColorModel model, int pixels[], int off, int scansize); void imageComplete(int status);
![]() | Note |
---|---|
The |
x, y
Specify the location within the image at which this rectangle begins.
w, h
Specify the width and height, in pixels, of this rectangle.
model
Specifies the color model used by the data in the pixels array.
pixels[]
Specifies an array of pixels.
offset
Specifies the index of the first pixel in the rectangle.
scansize
Specifies the width of each row in the pixels array.
Copyright © 1998-2009 Dilvan Moreira