问题描述
我正在尝试访问 BufferedImage
中的像素,该像素是使用 ImageIO.read(filePath)$ c从文件加载的$ c>,但是我得到此错误:
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_RGB
或 BufferedImage.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的图像类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!