Tech Tips: Compress Transparent PNGs with Flash
Do you use transparent PNGs in Flash, Flex or AIR? Want to cut your application file size in half?
Problem:
Embedding transparent PNGs dramatically increases the size of your Flash, Flex and AIR applications. Photoshop and Fireworks dot not have any compression available for transparent PNGs (that I am aware of).
Solution:
Import your PNGs into Flash, give them a linkage id, and export the file as a SWF. Make sure to set your compression level in the publish settings (default is 80%). Using this method, I was able to cut the file size in half for a number of applications.
-
[Embed(source="assets/images/images.swf#myImage.png")]
-
private var MyImage:Class;
-
private var myImage:BitmapAsset = new MyImage() as BitmapAsset;
or
-
[Embed(source="assets/images/images.swf#myImage.png")]
-
private var MyImage:Class;
-
private var myImage:BitmapAsset = new MyImage() as BitmapAsset;
rather than. . .
-
// Don't use this one
-
[Embed(source="assets/images/myImage.png")]
-
private var MyImage:Class;
-
private var myImage:BitmapAsset = new MyImage() as BitmapAsset;
It is also much easier to manage your external assets from a SWF. Designers can set up a nice slice sheet using the stage in Flash. Much easier than managing tons of small PNGs in folders everywhere.
Image Manager
In addition to using the SWF it can also be very useful to set up an ImageManager to serve out images to your application. This prevents having to change code in multiple places to update the same image reference.
Image Manager Class:
-
package com.cb.utils
-
{
-
import mx.core.BitmapAsset;
-
-
public class ImageManager
-
{
-
public static const MY_IMAGE_ID:String = "my_image_id";
-
-
[Embed(source="assets/images/images.swf#myImage.png")]
-
public static var MyImage:Class;
-
-
public static function getMovie(id:String):BitmapAsset
-
{
-
var result:BitmapAsset;
-
switch(id){
-
case MY_IMAGE_ID:
-
default:
-
result = new MyImage();
-
break;
-
}
-
return result;
-
}
-
}
-
}
To access an image from the manager class just make this call:
-
var myImage:BitmapAsset = ImageManager.getImage(ImageManager.MY_IMAGE_ID);
Importing PNGs into Flash
And for those of you that need a refresher on importing PNGs into Flash and setting up linkage IDs:

Select your file. Than go into the library. . .

Finally. . .

Enjoy!
Disclaimer: It may be obvious but you must be using transparent PNGs in your app to see a decrease in file size
Most of the apps I work on have lots of transparent PNGs!
This was originally posted on blackcj.com, Chris Black's personal blog. Chris is a Senior Developer at Sierra Bravo.

