user3369453
user3369453

Reputation: 21

How to read colors from an image

This is where I called the program to read the SpriteSheet, which was in another class.

private SpriteSheet spriteSheet = new SpriteSheet("/sprite_sheet.png");

This is where I tried to read the pixel colors from the sprite sheet which was colored with Black, Dark grey, Light grey, and White. This is meant to print out color details for the first row of pixels.

public SpriteSheet(String path) {
    BufferedImage image = null;

    try {
        image = ImageIO.read(SpriteSheet.class.getResourceAsStream(path));
    } catch (IOException e) {
        e.printStackTrace();
    }
    if(image==null){
        return;
    }

    this.path = path;
    this.width = image.getWidth();
    this.height = image.getHeight();

    pixels = image.getRGB(0, 0, width, height, null, 0, width);

    for(int i = 0; i<pixels.length;i++){
        pixels[i] = (pixels[i] & 0xff)/64;
    }
    for(int i=0; i<8;i++){
        System.out.println(pixels[i]);
    }

When I run this it does not print the numbers like I coded. How could I fix this? And how does the reading of colors work?

Upvotes: 0

Views: 170

Answers (1)

Jason C
Jason C

Reputation: 40315

If you aren't getting any output then either your println lines aren't getting reached or (far less likely) there's something wrong with your console configuration that is hiding output. We will assume, hopefully correctly, that all methods called here always either return or throw (i.e. nothing is hanging). Presuming the former, the only opportunity I see for that to happen is if the image fails to load and you return.

Since you print the stack trace of any exceptions but do not report seeing a stack trace, that means that ImageIO.read() must be returning null. For that to happen, according to the documentation:

The InputStream is wrapped in an ImageInputStream. If no registered ImageReader claims to be able to read the resulting stream, null is returned.

I do know that PNG is supported generally, but perhaps your specific flavor of PNG is not (e.g. a compressed, 4-color palette or something; I don't know what the limitations of ImageIO are here). I suggest you try saving the image in a different format, or testing with a more baseline PNG format (e.g. uncompressed 24-bit, no transparency, no interlacing).

If my analysis here is correct, the moral of this story is: Improve your error handling. Don't silently fail; especially when performing tasks that are critical to the correct functioning of your program.

If I am not correct, I suggest you either drop some debugging printouts in your method or step through in a debugger to see why those println lines aren't getting executed.

Upvotes: 1

Related Questions