For my platformer tile-based game I want to be able to load the game map from an image file.

Consider the following 25x15 px .png (enlarged) representing some level:

enter image description here

Assume that each specified color represents different game object. The actual hex values are irrelevant.

Given some input image, my map loading routine should be able to:

  • access the image's size in pixels
  • read specific [i, j]-th pixel's hex value

Is there some general rule which image format should I use? .png, .bmp, .jpg or something else?

  • \$\begingroup\$ How do you load your sprites anyway? What library/engine/framework do you use? Have you tried anything so far? \$\endgroup\$ – Vaillancourt Nov 25 '19 at 4:36
  • \$\begingroup\$ For anyone taking a similar approach on their project for any reason, make sure you pick a lossless image format, otherwise some of the pixels might be different colours and mess with the whole parsing process. \$\endgroup\$ – TomTsagk Nov 25 '19 at 11:01

If you want to keep things simple, I would pick a format and stick to it.

The two most simplest image formats that I know of are:

  • PPM
  • BMP
  • TGA

It's not that difficult to implement loading of any of these files. I see PPM files used a lot in ray tracing examples because the file format is so easy to handle. If you're the one generating these images, I'd highly recommend PPM to start out with. BMP would be a good alternative, if you won't want to go with PPM.

In terms of libraries, libpng is a popular choice. IMHO, it's interface is terrible and difficult to learn. If you can get over the learning curve though, it's a useful library.

stb_image.h is another popular choice it seems like. I've never used it, but it's easy to integrate and seems very cross-platform-ish. I can't speak to whether or not it's easy to learn, but it seems like another good choice. It's a single header file that you just put into your project and include it in the files that load image data.

  • \$\begingroup\$ Ah, why the down vote? \$\endgroup\$ – tay10r Nov 25 '19 at 1:47
  • 1
    \$\begingroup\$ +1 for stb_image. Very useful library that can easily be wrapped into an Image class. \$\endgroup\$ – Casey Nov 26 '19 at 15:28

I think: if you want to create levels using images for your engine, it's still better to have a more lightweight format: maybe just an array of bytes that represent positions and types of tiles. So I suggest to preprocess (bake) your 'any kind' of level image using some script (based on Python or JavaScript, for example) to your 'engine format'.

There are plenty of ways to write that kind of script for any kind of image format so I'm sure a simple Google search will reveal this to you.


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.