java images with alpha channel without using buffered image

老子叫甜甜 提交于 2019-12-24 11:26:06

问题


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?


回答1:


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.




回答2:


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 );
}


来源:https://stackoverflow.com/questions/2273730/java-images-with-alpha-channel-without-using-buffered-image

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!