【问题标题】:Some RGB values seem not to be convertable into a Color Object某些 RGB 值似乎无法转换为颜色对象
【发布时间】:2012-11-15 12:59:23
【问题描述】:

我有这种方法:

public void SaveImageOntoObject(String filepath) throws IOException {


      BufferedImage image = ImageIO.read(getClass().getResourceAsStream(filepath));
      this.width = image.getWidth();
      this.height = image.getHeight();
      this.ResetPointInformation();
      for (int row = 0; row < width; row++) {
         for (int col = 0; col < height; col++) {
            this.PointInformation[row][col] = new Color(image.getRGB(col, row));
        }
     }
  }

它将图像的文件路径作为输入,将每个像素的 RPG 值转换为颜色对象,然后将其存储到调用方法的对象的二维数组 PointInformation 中。

现在是我的问题:

虽然有些图片是这样的:

像魅力一样工作,其他人像这样:

让我以错误结束:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Coordinate out of bounds!
at sun.awt.image.ByteInterleavedRaster.getDataElements(ByteInterleavedRaster.java:318)
at java.awt.image.BufferedImage.getRGB(BufferedImage.java:888)
at Drawing.Object2D.SaveImageOntoObject(Object2D.java:75)** (that's the class whose object's my method works on)

为什么会这样?似乎 Java 无法将某些 RGB 值转换为颜色?

你能告诉我如何让它工作吗?

【问题讨论】:

  • 我怀疑代码将行与列混合在一起,并且第一张图像不会因为它是 100x100(正方形)而失败。为了尽快获得更好的帮助,请发帖SSCCE

标签: java image graphics colors rgb


【解决方案1】:

错误消息实际上是这样说的:“索引超出范围”。看来,你混淆了你的坐标和它们的界限。 getRGB 将参数 x (range 0 .. width) 作为第一,y (range 0 .. height) 作为第二。

this.width = image.getWidth();
this.height = image.getHeight();

for (int row = 0; row < height; row++) {        // swapped the ...
    for (int col = 0; col < width; col++) {     // ... bounds
        this.PointInformation[row][col] = new Color(image.getRGB(col, row));
    }
}

您的第一个示例的宽度 = 高度,因此问题不会出现。

【讨论】:

  • 您应该提到该方法本身将x作为第一个参数:getRGB(int x, int y)
猜你喜欢
  • 1970-01-01
  • 2013-12-10
  • 1970-01-01
  • 2019-02-08
  • 2013-06-15
  • 2016-05-04
  • 2017-09-11
  • 2012-01-18
  • 1970-01-01
相关资源
最近更新 更多