I am using Java with swing in FSE mode. I want to load a completely black-and-white image into binary format (a 2d array preferably) and use it for mask-based per-pixel collision detection. I don't even know where to start here, I've been researching for the past hour and haven't found anything relevant.
问题:
回答1:
Just read it into a BufferedImage
using ImageIO#read()
and get the individual pixels by BufferedImage#getRGB()
. A value of 0xFFFFFFFF
is white and the remnant is color. Assuming that you want to represent white as byte 0
and color (black) as byte 1
, here's a kickoff example:
BufferedImage image = ImageIO.read(new File("/some.jpg"));
byte[][] pixels = new byte[image.getWidth()][];
for (int x = 0; x < image.getWidth(); x++) {
pixels[x] = new byte[image.getHeight()];
for (int y = 0; y < image.getHeight(); y++) {
pixels[x][y] = (byte) (image.getRGB(x, y) == 0xFFFFFFFF ? 0 : 1);
}
}
See also:
- The Java Tutorials - 2D Graphics - Working with images
回答2:
If you're reading the image from a URL, it will already be in a binary format. Just download the data and ignore the fact that it's an image. The code which is involved in download it won't care, after all. Assuming you want to write it to a file or something similar, just open the URLConnection
and open the FileOutputStream
, and repeatedly read from the input stream from the web, writing the data you've read to the output stream.
You can also use ImageIO
if you are not downloading it from some resource.