2013-10-29 48 views
-1

目前我想获得一个图像像素的数组。现在,我使用这个代码:
Java nullpointerexception与bufferedimage.getrgb

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

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

但比我要使用的像素阵列它提供了一个NullPointerException。我以前使用过这个代码,没有任何错误。
它为什么会出现,我该如何做这项工作?

+0

'pixels'没有初始化,你刚才宣布它。 –

回答

0

的Class 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
+0

谢谢,这正是我想知道的 – Leeuwtje