【问题标题】:BufferedImage going out of boundsBufferedImage 超出范围
【发布时间】:2013-02-28 05:26:37
【问题描述】:

我目前正在尝试创建一个用纯色填充的形状,然后将其输出为 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());

我无法弄清楚为什么我的代码不起作用。有人有想法吗?

【问题讨论】:

  • xSizeySizeholding的值是多少?
  • 它们保存包含图像 x 和 y 轴坐标的整数值。我为每个参数传入 10。

标签: java image graphics awt bufferedimage


【解决方案1】:

如果您查看BufferedImagedocssetRGB(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)

这意味着,在您的情况下,xSizeySizewidthheight,并且您的 BI 不必具有 co-ordinates(xSize, ySize )。我希望你明白这里的意思。

【讨论】:

  • 啊。你同意我没有适当地使用缓冲图像吗?至少对于我正在尝试做的事情。
【解决方案2】:

你可能想要 bf.getGraphics().fillRect(...) 之类的东西

【讨论】:

    【解决方案3】:
    bf.setRGB(xSize, ySize, color.getRGB());
    

    setRGB 设置单个像素,x 坐标为 0 .. xSize - 1,y 坐标也一样。

    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 的光栅。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-27
      • 2012-05-04
      • 2018-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-09
      • 2014-02-25
      相关资源
      最近更新 更多