PNG Images

From The iPhone Wiki
Revision as of 22:27, 14 February 2021 by Dialexio (talk | contribs)
Jump to: navigation, search

The PNG images found on the iPhone cannot be viewed by a standard image viewer. Apple, for some unknown reason, implemented a non-standard PNG format that includes an extra data before the PNG header and compressed image data without the traditional headers and footers. In addition, the red blue pixels are flipped (BGRA instead of RGBA). All iPhone PNG images appear to follow this format.

Discussion

The PNG format consists of a header, followed by a set of data atoms, or chunks. According to the PNG spec, the 'IHDR', or PNG header chunk, should always come first. In Apple's iPhone format, a 'CgBI' chunk appears before the header. This chunk's data is four bytes long and contains a value of 0x40, or 48 decimal and is marked mandatory and private, which means that the data contained in the 'CgBL' chunk a third party extension to the PNG format that must be implemented by the parser. The purpose of this chunk, other than to signify that the PNG in iPhone format, is unknown. It could be a format version identifier.

Compressed image data, stored in the 'IDAT' chunk, contains deflate compressed data without the zlib headers, footers, or checksums that normal PNGs contain. When using zlib to decompress data, a negative value must be passed as the windowSize to use zlib's undocumented 'skip headers and crc' feature. There does not appear to be a good technical reason for using this format instead of the standard.

For some reason, the red and blue pixels are reversed in the deflated data. This could be an optimization to prevent the iPhone from having to do a pixel swap before writing the image to the screen buffer.

Converting to a standard PNG

To convert an iPhone PNG to a standard PNG:

  1. Remove the 'CgBl' chunk
  2. Decompress the data using zlib with the windowSize set to a negative number
  3. Swap the red pixel with the blue pixel in the data
  4. Recompress the data using zlib using the default headers and CRC
  5. Replace the image data chunk with the new compressed data in the PNG, and create a new checksum.

Tools

Apple includes a modified version of pngcrush with the iOS SDK that adds two additional arguments to convert PNGs to (--iphone) and from (--revert-iphone-optimizations) this modified format. Inside of Xcode.app, the modified version of pngcrush can be found at Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/pngcrush.

The format was also reverse-engineered, and third parties have created their own utilities to convert between formats. An example converter written in Python 2.x is available.[1]

Links