At some point of time during the process of coding your *awesome* iPhone application, you would have added some images to the project. The size-conscious among you fine folk might want to check the size of the image when it is embedded into the .app file. After all, you wouldn’t want to bloat the size of your app just to include a hi-res picture of your company’s logo. So does Xcode change the size of your image when you add it to the project?
Well yes it does…kinda…little bit. Xcode automatically optimizes your image only if it is in the PNG format. This is rather strange because .jpeg files generally occupy less space than .png files. Thus any PNG file added to the project is optimized during build time by an open-source tool called pngcrush. You can test this out by comparing the size of your .png file on the hard disk with the size of the file during run time. This is how you can do so:
- Control click on your file in Finder and click on Get Info. Here you will see the size of the file mentioned in bytes.
As you can see, the image size is 1063 bytes.
- Now add the same image to your Xcode project by dragging it to the Xcode icon. Check the “copy items into destination group’s folder” button and click on Add. Type the following lines of code and check the console for the result
UIImage *someImage = [UIImage imageNamed:@”image.png”];
NSLog(@”Image size in bytes:%i”,[UIImagePNGRepresentation(someImage) length]);
The result: Image size in bytes: 966
Thus the overweight image has been trimmed from 1063 bytes to a svelte 966 bytes. This process happens automatically and you cannot change the parameters of optimization. There are occasions when this optimization might distort the image when it is displayed. In such cases you can disable this optimization using either of the following methods:
- In your project window, control click on the image and chose Get Info. Then changed the type from “image.png” to “file”.
- In Xcode go to Project ->Edit Project Settings and click on the Build tab. Look for “Compress PNG Files” and uncheck the box. This will uniformly not perform any optimizations on your PNGs. Warning! The application icon of your app also will be affected.
Thus you have learnt about image optimization for PNG files in Xcode. Apple seems to favour the PNG format for the images on their device and we devs just have to deal with that. Now go add those hi-res images to your project and don’t feel guilty about it.