如何更改从文件加载的 BufferedImage 的图像类型? [英] How to change the image type of a BufferedImage which is loaded from file?

查看:36
本文介绍了如何更改从文件加载的 BufferedImage 的图像类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试访问使用 ImageIO.read(filePath) 从文件加载的 BufferedImage 中的像素,但出现此错误:

I'm trying to access the pixels in a BufferedImage which is loaded from a file using ImageIO.read(filePath), but I get this error:

Exception in thread "Game" java.lang.ClassCastException: java.awt.image.DataBufferByte cannot be cast to java.awt.image.DataBufferInt
    at com.package.graphics.Texture.<init>(Texture.java:29)
    at com.package.graphics.Texture.loadTexture(Texture.java:40)
    at com.package.Game.run(Game.java:71)
    at java.lang.Thread.run(Unknown Source)

在代码中,错误所在的行在构造函数中,如下所示:

In the code, the line which the error is on, is in the constructor and looks like this:

// Get the pixel array from the BufferedImage
this.pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();

据我所知,BufferedImage 不是 BufferedImage.TYPE_INT_RGBBufferedImage.TYPE_INT_ARGB 类型.因为我在游戏的其余部分使用这些类型,所以我想知道是否有办法将加载的图像从加载的类型转换"为另一种类型.
就我而言,我想将图像类型转换为 BufferedImage.TYPE_INT_ARGB.

As I understand this, the BufferedImage isn't of the type BufferedImage.TYPE_INT_RGB or BufferedImage.TYPE_INT_ARGB. Because I use these types in the rest of my game, I wonder if there is a way to 'convert' the loaded image from the type it was loaded as, to another.
In my case, I want to convert the image type to BufferedImage.TYPE_INT_ARGB.

推荐答案

用你想要的类型创建一个新的缓冲图像

Create a new Buffered image with the type you want

BufferedImage in = ImageIO.read(img);
BufferedImage newImage = new BufferedImage(in.getWidth(), in.getHeight(), BufferedImage.TYPE_INT_ARGB);

Graphics2D g = newImage.createGraphics();
g.drawImage(in, 0, 0, in.getWidth(), in.getHeight(), null);
g.dispose();

这篇关于如何更改从文件加载的 BufferedImage 的图像类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆