BufferedImage超出范围

时间:2013-03-12 15:43:11

标签: java image graphics awt bufferedimage

我正在尝试创建一个填充纯色的形状,然后输出为PNG。这是我的代码。

void CreateRedImage(int xSize, int ySize, String FileName){
        BufferedImage bf = new BufferedImage(xSize, ySize, BufferedImage.TYPE_INT_RGB);
        Color color = new Color(225, 000, 000);
        File f = new File(FileName + ".png");
        bf.setRGB(xSize, ySize, color.getRGB());
        try {
            ImageIO.write(bf, "PNG", f);
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

不幸的是,当我运行我的代码时,我收到此错误消息。

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Coordinate out of bounds!
    at sun.awt.image.IntegerInterleavedRaster.setDataElements(IntegerInterleavedRaster.java:301)
    at java.awt.image.BufferedImage.setRGB(BufferedImage.java:988)
    at ImageCreation.CreateBlueImage(ImageCreation.java:53)
    at Main.main(Main.java:12)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

现在,我知道问题在于:

bf.setRGB(xSize, ySize, color.getRGB());

我无法理解为什么我的代码不能正常工作。有人有个主意吗?

3 个答案:

答案 0 :(得分:2)

如果你查看BufferedImage的{​​{1>}的 setRGB(int x,int y,int rgb),它会说: -

  

将此BufferedImage中的像素设置为指定的RGB值。该   假设像素位于默认的RGB颜色模型TYPE_INT_ARGB中,   和默认的sRGB颜色空间。

它也说

  

如果坐标不在边界内,则可能抛出ArrayOutOfBoundsException。然而,   不保证显式边界检查。

表示您的xSizeySize不在BufferedImage的范围内。

<强>更新: -

再次从文档中,如果你仔细看到你碰巧使用的BufferedImage构造函数的签名,你会看到: -

public BufferedImage(int width, int height, int imageType)

这意味着,在您的情况下xSizeySizewidthheightBI和{{1}},而您的{{1}}不应该具有坐标(xSize,ySize)。我希望你明白这一点。

答案 1 :(得分:0)

bf.setRGB(xSize, ySize, color.getRGB());

setRGB设置一个像素,x coord为0 .. xSize - 1,y coord就像是明智的。

int c = color.getRGB();
for (int x = 0; x < xSize; ++x) {
    for (int y = 0; y < ySize; ++y) {
        bf.setRGB(x, y, color);
    }
}

或者

Graphics2D g = bf.createGraphics();
g.setColor(color);
g.fillRect(0, 0, xSize, ySize);
g.dispose();

或者更好的是使用BufferedImage的栅格。

答案 2 :(得分:0)

你可能想要像bf.getGraphics()。fillRect(...)

相关问题