我目前正在为游戏中的角色制作动态动画加载器,为此我需要检测当前帧是否完全空白以便停止加载更多精灵。这是我目前用来查明当前图像是否为空白的内容:
public static boolean isBlankImage(BufferedImage b) {
byte[] pixels1 = getPixels(b);
byte[] pixels2 = getPixels(getBlankImage(b.getWidth(), b.getHeight()));
return Arrays.equals(pixels1, pixels2);
}
private static BufferedImage getBlankImage(int width, int height) {
return new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
}
private static byte[] getPixels(BufferedImage b) {
byte[] pixels = ((DataBufferByte) b.getRaster().getDataBuffer()).getData();
return pixels;
}
但是,一旦我运行它,我就会遇到这个恼人的错误:
Exception in thread "Thread-0" java.lang.ClassCastException:
java.awt.image.DataBufferInt cannot be cast to java.awt.image.DataBufferByte
我试过切换铸造类型,但我得到的回报是:
Exception in thread "Thread-0" java.lang.ClassCastException:
java.awt.image.DataBufferByte cannot be cast to java.awt.image.DataBufferInt
我搜遍了整个地方寻找无济于事的答案,所以这是我的问题:有没有更好的功能方法来检查图像是否完全透明?
任何帮助将不胜感激。
该方法必须返回一个字节数组,您正在尝试转换DataBufferByte中的DataBuffer。我已将名称getPixels更改为getByteArray。既然不一样了。试试这个:
private static byte[] getByteArray(BufferedImage img) {
byte[] imageInByte = null;
String format = "jpeg"; //Needs a image TYPE
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(img, format, baos);
baos.flush();
imageInByte = baos.toByteArray();
baos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return imageInByte;
}
空白图像的DataBuffer
确实是DataBufferInt
的一个实例,而您的原始图像具有DataBufferByte
类型的缓冲区。您应该根据要比较的图像类型创建空图像:
private static BufferedImage getBlankImage(int width, int height, int type) {
return new BufferedImage(width, height, type);
}
并这样称呼它:
getBlankImage(b.getWidth(), b.getHeight(), b.getType())
请注意,就性能和内存使用而言,最好只创建一次空图像(或者对于每种可能出现的图像类型创建一次)。可能图像类型和大小是恒定的,并且在创建实际图像的任何地方都可以写入。
现在你有一个合适的空图像,可以测试它在Is there a simple way to compare BufferedImage instances?中的相等性:
public static boolean compareImages(BufferedImage imgA, BufferedImage imgB) {
int width = imgA.getWidth();
int height = imgA.getHeight();
// Loop over every pixel.
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
// Compare the pixels for equality.
if (imgA.getRGB(x, y) != imgB.getRGB(x, y)) {
return false;
}
}
}
return true;
}