Question

im drawing a bunch of tiles on a Canvas, these tiles are represented by either Images or BufferedImages.

i noticed that im getting millisecond draws with Images but what i start using BufferedImages for the tiles the frame time sky rockets to above 20ms.

BufferedImage buffered = ImageIO.read(new File(fileName));
Image image = Toolkit.getDefaultToolkit().createImage(fileName);

Both of these images support alpha channels. I would like to start using alpha capable Image's for intermediary buffers. However i havent found a place in the jdk that can generate them besides this Toolkit call to create one from a file.

Basically does anyone know how to create a blank Image (not BufferedImage) from scratch that can support alpha?

Was it helpful?

Solution

To answer your question directly:

// Create a empty BufferedImage which supports alpha
// It will be just as fast a Toolkit image
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

Some background:

It all comes down to the TYPE of BufferedImage you're using. BufferedImage offers a constructor in which you can specifiy the TYPE (INT_ARGB, 4BYTE_ARGB, etc). When using ImageIO, you do not have control over the type that gets used in construction of the BufferedImage. ImageIO uses type "0" which is custom. The TYPE governs how the image data is stored/accessed in memory which plays heavily into how the image is drawn/copied/blitted to the screen (or other image).

I created a simple test based on your code and the BufferedImage always renders VERY slowly. I create a second BufferedImage with TYPE_INT_ARGB and copied the first BufferedImage (from ImageIO) into it. This TYPE_INT_ARGB BufferedImage renders at the same speed as the Toolkit image.

OTHER TIPS

You can use the old ImageConsumer/ImageProducer API to create Image objects with any content you want.

This will create an Image object from ARGB pixels in the pix array with the given width and height:

public static Image createImage( int width, int height, int[] pix )
{
    return createImage( width, height, pix, 0, width );
}

public static Image createImage( int width, int height, int[] pix, int offs, int scan )
{
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    ImageProducer source = new MemoryImageSource( width, height, pix, offs, scan );
    return toolkit.createImage( source );
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top