Blog

Getting the size of a PNG without loading it

October 9, 2010 1 Comment

My current iPhone game (more info coming soon, I promise!) has a resource system that allows me to load texture maps when I need them and unload them when I don’t. This helps makes the game very memory efficient, but it had one annoying flaw. At program startup I had to load and unload several textures to get size information I needed to set up other game structures. To avoid this wasteful operation I started looking at ways to extract information from a png without loading the whole thing.

This StackOverflow discussion was useful, along with this guide to the png format from the W3C, but unfortunately, Apple threw a spanner in the works.

If you’ve been programming the iPhone for a while you’ll know that by default, Xcode premultiplies the alpha channel of PNG files before adding them to the application bundle. It also adds its own undocumented data chunk to the beginning of the file, breaking PNG guidelines which state that the IHDR chunk should always be at the beginning.

This Objective C function will return the size of an image for both standard and Apple PNGs. It scans through the file looking for the IHDR chunk, making no assumptions about its position. It should be easy enough to convert to other members of the C family.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <stdio.h>
 
//----------------------------------------------------------------------------
// GetPNGSize() - gets PNG Dimensions without loading any data
//----------------------------------------------------------------------------
BOOL GetPNGSize(const char *fileName,CGSize *pngSize)
{
    // PNG Signature
    unsigned char png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
    // IHDR chunk identifier
    unsigned char ihdr_signature[4]={'I','H','D','R'};
 
    FILE *fp;
    if( (fp = fopen(fileName,"rb")) == NULL )
    {
        return NO;
    }
 
    // load png signature and check it
    unsigned char sigBuf[8];
    fread(sigBuf, 1, 8, fp);
 
    if(memcmp(&sigBuf[0], &png_signature[0], 8))
    {
        fclose(fp);
        return NO;
    }
 
    // examine chunks until we find IHDR
    BOOL done = NO;
    while(!done && !feof(fp))
    {
        // get chunk length and type
        unsigned char chunkInfo[8];
        fread(&chunkInfo, 1, 8, fp);
 
        long length = (chunkInfo[0] << 24) | (chunkInfo[1] << 16) | (chunkInfo[2] << 8) | chunkInfo[3];
 
        // is this the IHDR?
        if(!memcmp(&chunkInfo[4], &ihdr_signature[0], 4))
        {
            unsigned char sizeInfo[8];
            fread(sizeInfo,1,8,fp);
 
            pngSize->width = (sizeInfo[0] << 24) | (sizeInfo[1] << 16) | (sizeInfo[2] << 8) | sizeInfo[3]; 
            pngSize->height= (sizeInfo[4] << 24) | (sizeInfo[5] << 16) | (sizeInfo[6] << 8) | sizeInfo[7];
            done = YES;
        }
        else 
        {
            // skip over the data and checksum and go to next chunk
            fseek(fp, length+4 , SEEK_CUR);
        }
    }
    fclose(fp);
    return done;
}
View Comments

AtlasMaker News

May 4, 2010 3 Comments

This is just a quick update for everyone wanting to know what’s happening with AtlasMaker. I have a new version planned, but I’m not quite sure when it’s going to get done. I wrote AtlasMaker over a couple of evenings to save me time with an iPhone game project I’m currently working on and that is taking priority at the moment.

The next version will hopefully contain the following features.

  • More/better error handling and a more robust and informative interface.
  • Several rectangle packing algorithms – choose the best one for your data.
  • Improved export file: more data, bigger text box for xml fragments etc.
  • You can choose the filename and location of the export file.
  • Optional flattening of layers on the finished document.

I was recently able to test AtlasMaker on CS4 (I developed it on CS2) and was dismayed by how slow it is in comparison. I managed to speed it up a bit by turning off “open documents in tabs”, but it still ran at a glacial pace.

I’m not sure what this means for the future of the project. It’s still quicker than making atlases it by hand, but I’m wondering if I should make the next-version-but-one a stand-alone program written in Python or C# or something. (I haven’t settled on a cross platform language for tool dev yet, but I am looking.)

Let me know what you think. Would you prefer a slow Photoshop script, or a faster external tool?

View Comments

Texture Atlas Maker

August 18, 2009 28 Comments

**2012 UPDATE**: I have released a new version of AtlasMaker with many more features.  Check it out here!

As I promised last time, here is a photoshop script for creating texture atlases from a directory of images. The script uses a rectangle packer class written by Iván Montes which is itself based on an article by Jim Scott. All I really did was add a GUI.

Texture Atlas Maker Photoshop Script

Instructions

AtlasMaker works in much the same way as the SpriteGrabber script I wrote a few weeks ago. Unzip the AtlasMaker directory somewhere, then in Photoshop,  go to File->Scripts->Browse and load AtlasMaker.jsx. The script should then run automatically.

Example Texture atlas created by AtlasMakerTo create a texture atlas, click browse and select the directory containing your textures. The script will then process each image to get the information it needs to make the atlas. Once this is done, you can modify your destination document size, or add an optional margin around each image. AtlasMaker will create as many pages as it needs to hold all the images.

When you are ready, click ok and AtlasMaker will generate the texture atlas, with each texture on its own layer. You should end up with something like the image on the left.

Datafile Export

If you tick the “Enable datafile export” checkbox, AtlasMaker will create a text file in the src directory called “AtlasInfo.txt”, containing a line of text for each sprite.

Each line is generated from the text entered into the “line template” edit box. Tags are used to substitute information about each sprite into the text.

#i – Image index (0.. number of Images in directory)

#filename – Filename of source image

#width – Sprite width

#height – Sprite height

#x – X position  of top left corner on spritesheet

#y – Y position of top left corner on spritesheet

#p – page number

Lets say your game engine loads textures or sprites like this: “TextureManager->GetTex(x,y,width,height);” and you have 50 images to load. You can generate all 50 calls by entering the following into the line template box:

TextureManager->GetTex(#x,#y,#width,#height);

SpriteGrabber will then generate 50 lines containing the correct coordinates and dimensions for each Image.

Download AtlasMaker

View Comments

SpriteGrabber – Photoshop Scripting for Game Development

June 9, 2009 4 Comments

One of the most common and tedious tasks in 2D game development is making sprite sheets from dozens or often hundreds of individual image files. Back when I was making Starblaster, I laid out several hundred sprites by hand. It took many, many hours and severely restricted my ability to experiment with different graphics. It’s even worse these days since most sprites use alpha channels; the semi-transparent images are almost impossible to line up by hand, and some particle effects are practically invisible unless they are laid on a dark background.

For my latest project (more info coming soon!) I decided I’d had enough of this drudgery, and wrote a Photoshop script to do the job for me.

SpriteGrabber v0.1

SpriteGrabber will take a directory full of image files and lay them out for you on one or more sprite sheets. Additionally, SpriteGrabber can export a text file containing information about each sprite. You can use this feature to generate calls to whatever function you use to load the sprites in your game.

Instructions

To run the script in Photoshop just go to File->Scripts->Browse and load the SpriteGrabber.jsx file from wherever you downloaded it to. It will run automatically and present you with the interface above.

Click “browse” and select the directory containing your sprites. SpriteGrabber will now process the directory and work out how many valid image files there are and how big the sprites are going to be. If you have different sized images in the directory, SpriteGrabber will use the largest dimensions to determine the sprite size.

Once the images are processed, the script will work out how many rows and columns there’ll be per page and how many pages will be needed to hold all the sprites. You can adjust the document width and height to alter these properties. Once you are happy, just click “Ok” to generate the sprite sheets.

Datafile Export

If you tick the “Enable datafile export” checkbox, SpriteGrabber will create a text file in the src directory called “SpriteInfo.txt”, containing a line of text for each sprite.

Each line is generated from the text entered into the “line template” edit box. Tags are used to substitute information about each sprite into the text.

#i – Sprite index (0.. number of sprites in directory)

#filename – Filename of source image

#width – Sprite width

#height – Sprite height

#x – X position  of top left corner on spritesheet

#y – Y position of top left corner on spritesheet

Lets say your game engine loads sprites like this: “SpriteManager->GetSprite(x,y,width,height);” and you have 300 sprites to load. You can generate all 300 calls by entering the following into the line template box:

SpriteManager->GetSprite(#x,#y,#width,#height);

SpriteGrabber will then generate 300 lines containing the correct coordinates and dimensions for each sprite. (This is probably a poor example as in real life you’d use a simple loop to do this, but it does illustrate how the feature works. The datafile export will come into its own when the next version is complete.)

The Future

SpriteGrabber is not intended as a masterclass in Photoshop scripting. In fact it’s the first script I’ve ever written, but it should help trim a few tedious hours off the development process. Soon I hope to have a new version ready that will be able to efficiently arrange sprites or textures of any size.

Download

SpriteGrabber has been tested on Photoshop CS2,CS4,CS5 for Windows Vista, and CS3,CS5 for Mac OS X.

View Comments