Reputation: 1003
I'm trying to print the value of each pixel, but it gives error when p = 300
.
Before p = 300
, all pixels are printed.
orignal.getHeight() = 344;
and orignal.getWidth() = 300;
.
BufferedImage binarized = new BufferedImage(original.getWidth(), original.getHeight(), original.getType());
int p, q;
System.out.println(original.getHeight() + "," + original.getWidth());
for(p=0;p<original.getHeight();p++)
{
for(q = 0; q < original.getWidth(); q++)
{
//System.out.println("goint to get pixel"+"("+p+","+q+")");
int Pixel = binarized.getRGB(p, q);
}
}
Error message:
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 Binarization.binarize(Binarization.java:137)
at Binarization.main(Binarization.java:20)
Is this some kind of memory allocation problem?
Upvotes: 0
Views: 207
Reputation: 9162
No, this means that you have an error in your logic.
You try to access an array element by index, which is greater than array size
Try changing the logic of the array retrieval:
int Pixel=binarized.getRGB(q,p);
This works because the method expects: getRGB(int width,int height), but you provide height, width to it
Upvotes: 7
Reputation: 1503180
Look at the documentation for BufferedImage.getRGB
public int getRGB(int x, int y)
Note that the x
value is the first parameter - that's the one which should be in the range [0, width). The y
value is the second parameter - that's the one which should be in the range [0, height). You've got them the wrong way round. I'm slightly disappointed that the exception isn't friendlier, admittedly.
It would be much clearer if you'd use x
and y
variables in your loop, too:
for (int y = 0; y < original.getHeight(); y++)
{
for (int x = 0; x < original.getWidth(); x++)
{
int pixel = binarized.getRGB(x, y);
// Use pixel
}
}
(Also note how I've declared x
and y
in the loops themselves; there's no point in declaring them beforehand. I've also added whitespace for readability.)
Upvotes: 3