【问题标题】:Java nullpointerexception with bufferedimage.getrgbjava nullpointerexception with bufferedimage.getrgb
【发布时间】:2013-11-08 19:06:59
【问题描述】:

目前我想获得一个包含图像像素的数组。我现在正在使用此代码:

int[] pixels;
int width = firstfloorimg.getWidth();
int height = firstfloorimg.getHeight();

firstfloorimg.getRGB(0, 0, width, height, pixels, 0, width);

但是,当我想使用像素数组时,它会给出 NullpointerException。我以前用过这段代码没有错误。
为什么会发生这种情况,我该如何进行这项工作?

【问题讨论】:

  • pixels 没有初始化,你刚刚声明了它。

标签: java arrays image nullpointerexception


【解决方案1】:

BufferedImage 类提供了getRGB() 方法的两种变体:

  1. 第一个int getRGB(int x, int y),它将按照返回类型的说明返回一个像素。

  2. 第二个

    int[] getRGB(int startX, int startY, int w, int h, 
                  int[] rgbArray, int offset, int scansize)
    

返回默认 RGB 颜色模型中的整数像素数组。但是,如果您传递的rgbArraynull,此函数将在其中创建一个新的rgbArray 并返回它:

public int[] getRGB(int startX, int startY, int w, int h,
                        int[] rgbArray, int offset, int scansize) {

    // other code      
    if (rgbArray == null) {
       rgbArray = new int[offset+h*scansize];
    }
   // other code
      return rgbArray;
    }

但同样,您必须在使用之前将返回的数组分配给pixels。在getRGB 函数中创建的数组在传递给此函数之前无法更改pixels 数组的引用,即null

考虑在第二个函数上使用getPixel(x, y) 函数,因为与第二个函数不同,getPixel(x, y) 不会丢弃 Java2D 所做的优化。讨论它超出了这个问题的范围。

参考:

  1. BufferedImage.getRGB

【讨论】:

  • 谢谢,这正是我想知道的
猜你喜欢
  • 2015-03-24
  • 2012-04-13
  • 2022-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多