Java- How would I load a black and white image into binary?

╄→尐↘猪︶ㄣ 提交于 2019-12-06 09:15:34

问题


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.



来源:https://stackoverflow.com/questions/5925426/java-how-would-i-load-a-black-and-white-image-into-binary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!