java - getSubimage() 方法中出现越界异常

标签 java bufferedimage

我编写了一小段代码来将 Sprite 表分割成单独的图像......

private BufferedImage sheet, dirt, grass, rock, tree, water;

    int width = 64, height = 64;

        public void split() {
            dirt = sheet.getSubimage(0,0,width,height);
            grass = sheet.getSubimage(width,0,width*2,height);
            rock = sheet.getSubimage(width*2,0,width*3,height);
            tree = sheet.getSubimage(0,height,width,height*2);
            water = sheet.getSubimage(width,height,width*2,height*2);
        }

现在,前两个(泥土和草)如预期顺利进行。然而,问题在于岩石裁剪线。由于某种原因它会抛出异常...

” 线程“Thread-0”java.awt.image.RasterFormatException 中的异常:(x + width) 位于 Raster 之外
在 sun.awt.image.ByteInterleavedRaster.createWritableChild(ByteInterleavedRaster.java:1245)

"

很明显,问题与 x 值“越界”有关。但 x 值是(宽度 * 2),即 128pix,这完全在该图像(192x128)的范围内,我已将其作为证据附在其中。

我还对代码进行了一些更改,以将岩石的 x 值为 1 进行裁剪,但我仍然遇到问题,与对另一个 bufferedImage 使用相同的尺寸相同。

第一次发帖,有什么不对的地方请见谅。

提前致谢

The image

最佳答案

回答我的评论。

所以您走在正确的道路上,但不太了解 getSubimage() 的工作原理。

文档说

Parameters:

x - the X coordinate of the upper-left corner of the specified rectangular region

y - the Y coordinate of the upper-left corner of the specified rectangular region

w - the width of the specified rectangular region

h - the height of the specified rectangular region

您正确设置了 xy 值,但是您错误地设置了 widthheight > 值(value)观。

由于您从点 (x,y) 开始,因此不需要像您一样补偿 宽度高度 ,而不是直接使用它们。

所以,你的代码将是

public void split() {
            dirt = sheet.getSubimage(0,0,width,height);
            grass = sheet.getSubimage(width,0,width,height);
            rock = sheet.getSubimage(width*2,0,width,height);
            tree = sheet.getSubimage(0,height,width,height);
            water = sheet.getSubimage(width,height,width,height);
        }

关于java - getSubimage() 方法中出现越界异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39651319/

相关文章:

java - 对称密码学解密问题

java - 如何从另一个类为 TextView 设置文本?

java - 灰度 BufferedImage 的图形/文件输出

java - 从 BufferedImage 获取文件名

java - 如何使用 Spring RestTemplate 处理传输编码分块 json

java - 在使用页面工厂和 selenium webdriver 实现页面对象建模时,这两种方法中哪一种是更好的方法?

java - 如果我在创建对象时已经打开连接,是否需要执行 HTTPUrlConnection.connect() ?

尝试从 String 转换为 PNG 时由 ZipException 引起的 Java IIOException

java - 如何将字节数组转换为缓冲图像

java - 检测 BufferedImage 是否包含透明像素