0
\$\begingroup\$

I want to let players of my top-down game save, load and share worlds as PNG images. How do I read the colors in a PNG file or change them?

I imagine something like this:

BufferedImage mapImg = ImageLoader.loadImage(path);

// (then, later)

for(x = 0; x < mapImg.width; x++) {
    for(y = 0; y < mapImg.height; y++) {
        // Look up the color at this position
    }
}

Here is my ImageLoader class:

public class ImageLoader {

    public static BufferedImage loadImage(String path) {
            try {
                return ImageIO.read(ImageLoader.class.getResource(path));
            } catch (IOException e) {
                e.printStackTrace();
                 System.exit(1);
            }
            return null;
    }
}
\$\endgroup\$
1
\$\begingroup\$

That is right idea for reading/writing images but you'll want to get your "ImageLoader" class from a library, which will then give you a regular bitmap in memory to work with. The layout of that bitmap class is going to depend on the library you use.

To see why, or what you need to handle if you want to write your own, see the W3C PNG Specification.

\$\endgroup\$
  • \$\begingroup\$ Here is the code from that class... I'm not quite sure what you mean @jzx Sorry for stupid public class ImageLoader { public static BufferedImage loadImage(String path){ try { return ImageIO.read(ImageLoader.class.getResource(path)); } catch (IOException e) { e.printStackTrace(); System.exit(1); } return null; } } \$\endgroup\$ – thedobbles Mar 6 '15 at 18:17
  • 2
    \$\begingroup\$ @thedobbles You can edit your question to include additional information. \$\endgroup\$ – MichaelHouse Mar 6 '15 at 18:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.