3

I am reading a file and trying to get image width and height. However, I am getting an exception whenever I am calling this line

inImg.getRaster().getPixels(0,0,width,height,pixels);

The exception I am getting is

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 307200
at sun.awt.image.ByteInterleavedRaster.getPixels(ByteInterleavedRaster.java:1014)
at sobel_java.main(sobel_java.java:22)

My code is

public class Sobel {   

 public static void main(String[] args) throws IOException{   

  int     i, j;   
  double  Gx[][], Gy[][], G[][];   
  FileInputStream inFile = new FileInputStream("lena.bmp");   
    BufferedImage inImg = ImageIO.read(inFile);   
    int width = inImg.getWidth();   
    int height = inImg.getHeight();   
    int[] pixels = new int[width * height];   
    int[][] output = new int[width][height];   
    inImg.getRaster().getPixels(0,0,width,height,pixels);  

}} 

Thanks for your help.

  • This link is helpful : http://stackoverflow.com/questions/6524196/java-get-pixel-array-from-image – VIjay J Dec 15 '15 at 08:03
  • Try to log the size of the value returned by getRaster() an the size of your pixels array, as well as height and width parameters, it will help you find out what doesn't fit there – Yury Fedorov Dec 15 '15 at 08:06

1 Answers1

2

getPixels() method stores all samples of your raster into the output array, more than one per pixel. You can get number of samples per pixel using getNumBands(). Increase the length of your output array:

int numBands = inImg.getRaster().getNumBands();
int[] pixels = new int[width * height * numBands];
vojta
  • 5,591
  • 2
  • 24
  • 64