So, I'm trying to the color of a specific pixel in an BufferedImage...
public void LoadImageLevel (BufferedImage image) {
int w = image.getWidth ();
int h = image.getHeight ();
System.out.println (w + " " + h);
for (int xx = 0; xx < h; xx++) {
for (int yy = 0; yy < w; yy++) {
int pixel = image.getRGB (xx, yy);
int red = (pixel >> 16) & 0xff;
int green = (pixel >> 8) & 0xff;
int blue = (pixel) & 0xff;
if (red == 255 && green == 255 && blue == 255) {
handler.addObject (new Block (xx * 32, yy * 32, ObjectID.Block, 32, 32));
}
}
}
}
And it's called from the Main class constructor:
ImageLoader imageLoader = new ImageLoader ();
level = imageLoader.loadImage ("/levels/level_test.png");
LoadImageLevel (level);
The BufferedImage is loaded from my BufferedImageLoader class:
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ImageLoader {
private BufferedImage image;
public BufferedImage loadImage (String path) {
try {
image = ImageIO.read (getClass ().getResource (path));
} catch (IOException e) {
e.printStackTrace ();
}
return image;
}
}
When I run the project I get this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Coordinate out of bounds!
at sun.awt.image.ByteInterleavedRaster.getDataElements(Unknown Source)
at java.awt.image.BufferedImage.getRGB(Unknown Source)
at com.main.index.Game.LoadImageLevel(Game.java:190)
at com.main.index.Game.<init>(Game.java:41)
at com.main.index.Game.main(Game.java:206)
Line 190 is the "int pixel = image.getRGB (xx, yy);", line 41 is where it's called in the constructor, and line 206 is the main method.
Thanks in advance! ^_^
Problem is here:
int pixel = image.getRGB (xx, yy);
It should be:
int pixel = image.getRGB (yy, xx);
Your xx
goes from 0 to the height, instead of going from 0 to the width. Your yy
goes from 0 to the width, instead of going from 0 to the height.
level = imageLoader.loadImage ("/levels/level_test.png");
The Image you are using should be less than total Width and Height of main Window . And In this case Where RGB values are taken A picture with size of 2^X where X = 1,2,3,4,5,6,7,8,9.... ..
Try this : resize level_test.png to 512 by 512 pixels.
Above is solution for this as Array contains boundaries.
java.lang.ArrayIndexOutOfBoundsException: Coordinate out of bounds!
at sun.awt.image.ByteInterleavedRaster.getDataElements(Unknown Source)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.