java image数组,打开像素数组与Java的ImageIO的Image对象?

I'm currently turning an array of pixel values (originally created with a java.awt.image.PixelGrabber object) into an Image object using the following code:

public Image getImageFromArray(int[] pixels, int width, int height) {

MemoryImageSource mis = new MemoryImageSource(width, height, pixels, 0, width);

Toolkit tk = Toolkit.getDefaultToolkit();

return tk.createImage(mis);

}

Is it possible to achieve the same result using classes from the ImageIO package(s) so I don't have to use the AWT Toolkit?

Toolkit.getDefaultToolkit() does not seem to be 100% reliable and will sometimes throw an AWTError, whereas the ImageIO classes should always be available, which is why I'm interested in changing my method.

解决方案

You can create the image without using ImageIO. Just create a BufferedImage using an image type matching the contents of the pixel array.

public static Image getImageFromArray(int[] pixels, int width, int height) {

BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

WritableRaster raster = (WritableRaster) image.getData();

raster.setPixels(0,0,width,height,pixels);

return image;

}

When working with the PixelGrabber, don't forget to extract the RGBA info from the pixel array before calling getImageFromArray. There's an example of this in the handlepixelmethod in the PixelGrabber javadoc. Once you do that, make sure the image type in the BufferedImage constructor to BufferedImage.TYPE_INT_ARGB.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值