Adobe
Products
Acrobat
Creative Cloud
Creative Suite
Digital Marketing Suite
Digital Publishing Suite
Elements
Photoshop
Touch Apps
Student and Teacher Editions
More products
Solutions
Creative tools for business
Digital marketing
Digital media
Education
Financial services
Government
Web Experience Management
More solutions
Learning Help Downloads Company
Buy
Home use for personal and home office
Education for students, educators, and staff
Business for small and medium businesses
Licensing programs for businesses, schools, and government
Special offers
Search
 
Info Sign in
Welcome,
My cart
My orders My Adobe
My Adobe
My orders
My information
My preferences
My products and services
Sign out
Why sign in? Sign in to manage your account and access trial downloads, product extensions, community areas, and more.
Adobe
Products Sections Buy   Search  
Solutions Company
Help Learning
Sign in Sign out My orders My Adobe
Preorder Estimated Availability Date. Your credit card will not be charged until the product is shipped. Estimated availability date is subject to change. Preorder Estimated Availability Date. Your credit card will not be charged until the product is ready to download. Estimated availability date is subject to change.
Qty:
Purchase requires verification of academic eligibility
Subtotal
Review and Checkout
Adobe Developer Connection / Flash Developer Center /

Optimizing transparent images for projects in Flash using ActionScript 3

by Ben Smith

Ben Smith
  • AgencyNet
  • spilled-milk.com

Created

22 June 2010

Page tools

Share on Facebook
Share on Twitter
Share on LinkedIn
Bookmark
Print
Flash Professional graphic effects

Requirements

Prerequisite knowledge

A basic understanding of coding with the ActionScript 3 syntax is required. Prior experience working with Flash Professional and Photoshop is helpful.

User level

Beginning

Required products

  • Flash Professional CS5 (Download trial)
  • Photoshop Extended (Download trial)

Sample files

  • png_from_jpg.zip (263 KB)

The ideal image format to use when building web apps is, hands down, the Portable Network Graphics (PNG) file format. Besides using lossless data compression, the PNG image format offers the following benefits:

  • Supports 32-bit ARGB color channel palettes (alpha channel data)
  • Maintains color precision
  • Displays gradients and smooth color transitions

These are just a few of the reasons this format is used most often by designers when displaying logos, Flash assets, and graphics for the web. The only downside I've noticed with using PNG files is the slightly increased file size that is the result of the extra 8-bit (alpha channel data information) that it supports.

In this article, I describe a strategy for using ActionScript 3 to optimize graphic assets in your Flash projects. By following these instructions, you'll learn how to use two JPEG files to reproduce the alpha channel of a PNG file. This technique enables you to reduce the file size of images rendered in Flash by leveraging the PNG file format's support for transparency.

Generating JPEG source files and importing them into Flash

Although bandwidth is ever increasing, there are still many reasons why you should strive to develop projects with the smallest possible file size. With the latest trends of mobile and wireless devices, it's difficult to predict the bandwidth available to your target users. Delivering an app with optimized graphics (making it faster and easier to download) is always a good goal to achieve, regardless of the platform.

Since Flash is the leader in delivering rich media advertising, the element that typically increases the file size the most in a project is the visual content, or more specifically the image files used for display.

Portable Network Graphic (PNG) files are most commonly used when transparency is required for a design. However, including PNG files often causes an increase in a project's file size because of the extra channel required for the alpha information, even if there is only a very small area of transparency in the image. While transparency is a necessity for complex layouts, every pixel in the graphic has one byte of extra data added to support the transparent areas. For example, a transparent 100 × 100 pixel PNG image is 10 KB of lossless information larger than a non-transparent image of the same size, due to the alpha channel. You can imagine how this could potentially increase, adding to the size of your project as well as the individual file sizes of the PNG images. (A transparent PNG file that's 500 × 500 pixels contains 250 KB of added lossless information.)

It is possible to achieve the same effect of a PNG file set with alpha transparency by mapping two JPEG files together with ActionScript at runtime to produce the alpha channel. To accomplish this, you need the two JPEG source files—one to hold all the pixels that will need to be visible, the original, and one to act as the mask for those pixels, the matte—and a small amount of code to merge the exact pixels from both original and matte into a final transparent image.

Creating the original JPEG

To follow along with these instructions, do one of the following:

  • Use Photoshop to open one of your own 32-bit PNG files with transparency enabled.
  • Download the sample files folder, uncompress the folder, and open the masterImage.png file (located in the sample_project/original folder) in Photoshop.

Note: The sample_project folder contains a file named Readme.txt with information about the folder structure of this project. Be sure to read it before continuing with these instructions.

The sample_project folder will be your work environment. The folder structure is set up to mirror that of the folder labeled completed, located at the same root level. The sample project contains the masterImage.png which is referenced within this tutorial, or you can replace that with one of your own.

Follow these steps:

  1. View the file in Photoshop to confirm that the image contains transparent areas.
  2. Choose Layer > New Fill Layer > Solid Fill. In the dialog box that appears, choose white.
  3. In the Layers panel, drag the new fill layer down, placing it beneath the original PNG file graphic with transparency. Rename this layer WhiteLayer. After adding this white background layer, you will no longer see the transparency, but the new white background (see Figure 1).
White, rather than a checkerboard pattern, indicates that the white fill layer has replaced the transparent areas of the original graphic.
Figure 1. White, rather than a checkerboard pattern, indicates that the white fill layer has replaced the transparent areas of the original graphic.
  1. In the Save for Web & Devices dialog box, set the format to JPEG and click Save.
  2. In the Save Optimized As dialog box, navigate to the sample files folder you downloaded previously and save the JPEG file as Original.jpg in the new_images folder (located in the sample_project folder of the sample files). Click Save.
  3. Check the file size of the exported JPEG, and note that its file size is much smaller (approximately 29 KB, compared to the master PNG file size of 82 KB) because it takes advantage of the lossy compression that the JPEG file format supplies.

Creating the matte image

In this part, you'll create the matte (a black and white image) that will contain the data about which parts of the Original.jpg pixel data should show through (as though transparent) and what parts should be displayed (the opaque graphics).

Follow these steps:

  1. Back in Photoshop, open the original masterImage.png file again, if it is not already open. Leave the bottom layer (WhiteLayer) at the bottom because you'll use it later.
  2. In the Layers panel, select the top layer (Layer 0) that contains the image with the tree.
  3. Choose Layer > New > Layer. In the New Layer dialog box, enter the name for the new layer: clipping mask.
  4. While the clipping mask layer is still selected, choose Edit > Fill. In the Fill dialog box, select black as the fill color, with normal blending mode and 100% opacity. Click OK.
  5. In the Layers panel, right-click the clipping mask's layer name and select Create Clipping Mask from the menu that appears (see Figure 2). After setting the black fill as a clipping mask, the graphic elements in the image are black and the areas that were transparent are displaying the white background layer.
Choosing the Create Clipping Mask option in the menu that appears.
Figure 2. Choosing the Create Clipping Mask option in the menu that appears.

Note: If desired, you can temporarily hide the white background layer to confirm that the black clipping mask on the top contains areas of transparency, with the checkerboard pattern showing through. Be sure to turn the visibility of the bottom white layer back on before continuing.

  1. The only remaining task is to merge all of the layers together into one complete layer. Press Control+Shift+E (Windows) or Command+Shift+E (Mac) to merge all three layers into one.
  2. Choose Image > Mode > Grayscale. In the dialog box that appears, click Discard to discard the color information and set the file's current color mode to grayscale.
  3. Press Control+I (Windows) or Command+I (Mac) to invert the colors (see Figure 3). At this point, the edited image is comprised of a single layer that contains only white, gray and black, rather than displaying the original colors of the image.
 After inverting the colors, the items that were black are now white and vice versa.
Figure 3. After inverting the colors, the items that were black are now white and vice versa.
  1. Choose File > Save for Web & Devices to save this image as a JPEG file. In the Save for Web & Devices dialog box, select the JPEG file format. Click Save.
  2. Navigate to the sample_project folder and save this new JPEG file in the same folder (new_images) as the Original.jpg file you created in the previous section. In the Save As field, enter the name of the file: GrayScale.jpg. Click Save.

Using these two JPEG images (Original.jpg and GrayScale.jpg), you'll recreate the appearance of the original transparent PNG graphic with ActionScript at runtime.

Creating the FLA file for exporting the ActionScript and image data

There are still a few more steps to create and edit the Flash file before you add the code. Follow these steps:

  1. Launch Flash and choose File > New and create a new Flash File (ActionScript 3.0) to create the FLA file. Click OK.
  2. Choose File > Save and save the file. Use the Save dialog box to navigate to the sample_project folder, and then save the new FLA file in the flash/bin folder. Name the file BuiltPNG.fla and click Save.
  3. Choose File > Import > Import to Library. In the Import to Library dialog box, browse to select the files in the new_images folder that you created earlier (Original.jpg and GrayScale.jpg). Press Shift to select both files and then click Open.
  4. Open the Library (Window > Library). Right-click the GrayScale.jpg file. In the context menu that appears, select Properties. In the section labeled Linkage, select the check box next to the Export for ActionScript option. The Export in frame 1 option is also enabled by default when you choose to enable the Export for ActionScript feature.
  5. Flash populates the field labeled Class with the filename of the image (GrayScale.jpg). Rather than using that image file name, you'll use a simpler Class name. Highlight GrayScale.jpg in the Class field, and enter Grayscale.
  6. Click OK to save the changes to the Linkage settings and then click OK once again in the alert message that appears:

    A definition for this class could not be found in this class path, so one will automatically be generated in the SWF file upon export.

  7. Repeat Steps 4–6 on the imported file named Original.jpg. In the Class field, enter the new class name Original.

In the next section, you'll add the ActionScript code to convert the two JPEG graphics and make them appear as though they are a single PNG file with transparency.

Adding the code that merges the two JPEG files

In the first part of this article, you created two JPEG files using the same PNG file:

  • Original.jpg contains the color pixel graphic content; the transparent areas are filled with white
  • GrayScale.jpg is a grayscale inverted mask; the transparent areas are filled with black

You also created a new Flash file. Then you imported the two files listed above and set the Linkage properties of both JPEG files to Export for ActionScript to make the image data available to the SWF at runtime.

In this section, you'll create a new class file that contains the code to merge the two JPEG images and generate the alpha channel. Follow these steps:

  1. In Flash, choose File > New > ActionScript File to create an ActionScript file. Click OK.
  2. Copy the following code to your Clipboard:
package { //import the necessary definitions import flash.display.Bitmap; import flash.display.BitmapData; import flash.utils.ByteArray; public class ColorAndAlphaCompared extends Bitmap { //variable to hold our grayscale bitmap private var _greyScale:BitmapData; //variable to hold our colored bitmap private var _coloredImage:BitmapData; //variable to hold the resultant bitmap private var _newBitmapData:BitmapData; //variable to hold the our greyscaleImagePixels private var _origVector:Vector.<uint>; //variable to hold the our coloredImagePixels private var _colorVector:Vector.<uint>; private var _vector:Vector.<uint>; //pass in references to our colored & grayscale images into our constructor. public function ColorAndAlphaCompared(bitmapData : BitmapData,greyScaled : BitmapData) { _vector = new Vector.<uint>(); _greyScale=greyScaled; _coloredImage=bitmapData; //instantiate new BitmapData with the width & height of either of our jpg references and set its transparent property to true. _newBitmapData=new BitmapData(greyScaled.width,greyScaled.height,true,0x00000000); /*use the lock method on our newBitmapData to prevent our redraws as we add new pixels to it*/ _newBitmapData.lock(); /*pass our bitmapData into the constructor of the super class this class extends. (Bitmap class)*/ super(_newBitmapData); /*store the pixels of the entire bounds of our greyScale image*/ _origVector=_greyScale.getVector(_greyScale.rect); /*since we will never adjust the vectors length set its fixed value to true*/ _origVector.fixed=true; /*store the pixels of the entire bounds of our coloredImage*/ _colorVector=_coloredImage.getVector(_coloredImage.rect); /*set the fixed variable to true*/ _colorVector.fixed=true; /*begin the analysis of the two vectors*/ readWrite(); } /*readWrite: * This method will loop through each index of both our vectors and store the * analyzed version into a final vector */ protected function readWrite():void { /*how many times do we need to analyze our data*/ var totalPixels:int=_colorVector.length; var i:int=0; /*define the length of our resultant vector*/ _vector.length=totalPixels; /*set fixed property to true*/ _vector.fixed=true; /*loop through all pixels until 0 is reached*/ while (--totalPixels) { /*set the current index of the vector to the result of the two analyzed pixels*/ _vector[totalPixels]=int(shiftPixels(int (_origVector[totalPixels]),int(_colorVector[totalPixels]))); } /* end of our loop*/ /* set the new pixels into the bound area of our _newBitmapData*/ _newBitmapData.setVector(_newBitmapData.rect, _vector); /* unlock _newBitmapData so that the player will redraw the new content*/ _newBitmapData.unlock(); /*rid the unused content to to free up memory*/ dispose(); } /*shiftPixels: *This method accepts two different pixels. One to represent the value of *alpha and the other merely as the color value. The two pixels are merged *into a resulting 32bit ARGB value and returned to the caller of the *method. */ private function shiftPixels(alphaChannel : uint,colorChannel : uint):uint { /*extract the blue channel from the pixel representing the alpha value*/ var decimal:uint=alphaChannel>>16&0xFF; /*prepend our blue channel as the alpha of our colorChannel pixel*/ var argb : uint = (decimal << 24) | (ColorAndAlphaCompared.extractRED(colorChannel)<<16) | (ColorAndAlphaCompared.extractGREEN(colorChannel)<<8) | ColorAndAlphaCompared.extractBLUE(colorChannel); /*return the combined ARGB value*/ return argb; } /*Dispose: *This method frees up memory used when creating the Transparent image */ private function dispose():void { /*rid the greyScale image*/ _greyScale.dispose(); /*rid the _coloredImage image*/ _coloredImage.dispose(); /*remove the vectors*/ _vector=_colorVector=_origVector=null; /*remove references to our jpgs*/ _greyScale=_coloredImage=null; } /*extractAlpha: *This method extracts the alpha value of a supplied hex value */ static private function extractALPHA(hex : uint):uint { return hex >> 24 & 0xff; } /*extractRED: *This method extracts the red value of a supplied hex value */ static private function extractRED(hex : uint):uint { return hex >> 16 & 0xff; } /*extractGREEN: *This method extracts the green value of a supplied hex value */ static private function extractGREEN(hex : uint):uint { return hex >> 8 & 0xff; } /*extractBLUE: *This method extracts the blue value of a supplied hex value */ static private function extractBLUE(hex : uint):uint { return hex & 0xff; } } }
  1. Click the Script window to select it and then paste the code you copied above.
  2. Choose File > Save. In the Save dialog box, name the file ColorAndAlphaCompared.as. Navigate to the sample_project/flash/src folder and click Save to save the new class file.

You have now successfully generated the ActionScript class that utilizes the bitmap data of the two JPEG files to create an alpha channel.

Creating the document class

In this section, you'll create one more ActionScript class file. This serves as the document class for the FLA file named BuiltPNG.fla that you saved in the sample_project/flash/bin folder.

Follow these steps:

  1. In Flash, choose File > New > ActionScript File to create another ActionScript file.
  2. Choose File > Save. In the dialog box that appears, name the file FullColor.as and browse to save it in the sample_project/flash/src folder, alongside the ColorAndAlphaCompared.as file you created in the last section. Click Save.

    This class is not only the base class for the BuiltPNG.swf, but also contains the code that connects the images imported into the Library to the ColorAndAlphaCompared class. This is also the class that displays the combined results of the two merged JPEG files.

  3. Copy the code below to the Clipboard:
package { //import the necessary definitions import ColorAndAlphaCompared; import flash.display.Sprite; public class FullColor extends Sprite { public function FullColor() { /*add the instance of ColorAndAlphaCompared to our DisplayList and pass in the references to our colored image & grayscale Image)*/ addChild(new ColorAndAlphaCompared(new Original(1,1),new Grayscale(1,1))); } } }
  1. Return to Flash and click the Script window to select it. Paste the copied code.
  2. Choose File > Save to save the changes to the file.

Testing the results of the merged JPEG files

At this point, all the pieces are in place. The last step is to hook up the project's document class and test the movie to see the results. Follow these steps:

  1. Locate the sample_project/flash/bin folder and open the file in the named BuiltPNG.fla in Flash, if it is not already open.
  2. Click the Stage and open the Property inspector (Window > Properties).
  3. In the Publish section, Enter the name FullColor in the Class field.
  4. Click the Edit button located directly below the pencil icon to reveal the Publish Settings dialog box.
  5. Click the Settings button next to the ActionScript 3.0 menu. In the Advanced ActionScript 3.0 Settings dialog box, click the Plus (+) icon. In the field that appears (the second folder down) type ../src to update the source path. This step ensures that both of the classes in the src folder will be referenced by the published SWF file named BuiltPNG.swf. Click OK to close the Advanced ActionScript 3.0 Settings.
  6. In the Publish Settings dialog box, click Publish to create the SWF file. (It will be saved in the bin folder, alongside the BuiltPNG.fla file).

Flash Player loads to display the results. The image data of the two JPEG files has been combined to form a transparent image, which closely resembles the original masterImage.png you opened at the beginning of this sample project. If desired, you can return to Flash, change the Stage color of the BuiltPNG.fla file and publish the file again. You'll see that the color of the Stage shows through the areas that were transparent in the original PNG file (see Figure 4).

Color of the Stage showing through the transparent areas of the image
Figure 4. Color of the Stage showing through the transparent areas of the image

The FullColor.as file instantiates the ColorAndAlphaCompared class and passes in a reference to both JPEG files, which are located in the SWF's Library.

The ColorAndAlphaCompared.as file programmatically manipulates the two JPEG source files into a new Bitmapdata with an alpha channel. Because the ColorAndAlphaCompared class extends the Bitmap class, the FullColor.as file adds the instance of the returned bitmap to the Stage. When the final image is rendered, it is immediately visible.

The ColorAndAlphaCompared class accepts two BitmapData files. In this example, it accepts a grayscale image file and a full color image file. The code extracts a 32-bit pixel value for every pixel that both images contain. After extraction, the pixel values of both images are systematically added together to generate a new 32-bit pixel image.

Since the grayscale JPEG image you created is only one color, you could use any channel to represent the alpha channel. This is possible because all three channels hold the exact same information. Next, through the use of binary shifting (bits being shifted to the left or right) the eight bits of data that were extrapolated from the grayscale image are shifted left by 24 bits (which is the equivalent of being multiplied by 16,777,216). This places those eight bits in the alpha channel where the code then appends the Red, Green, and Blue channels of the original image. This process forms an ARGB 32-bit pixel bitmap object. Finally, after each pixel is examined, the final bitmap is drawn and added to the Stage.

Where to go from here

Try experimenting with these two classes, using a wide variety of different images in a range of file sizes. Be sure to check the original and resulting file sizes to see how dramatically you can reduce the file size of bitmap assets in your Flash projects.

Creative Commons License
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License

More Like This

  • Pixel Bender basics for Flash
  • Creating graphic effects using the new Deco scripts in Flash Professional CS5
  • Creating movie clips with reflections in ActionScript 3.0
  • Exploring the Spring tool in Flash Professional CS5
  • Webcam Motion Detection: Using the BitmapData API in Flash 8
  • Flash glossary: Gradient Transform tool
  • Flash glossary: Free Transform tool
  • Flash glossary: Deco tool
  • Flash glossary: Spray Brush tool
  • Flash glossary: Filters

Flash User Forum

More
04/23/2012 Auto-Save and Auto-Recovery
04/23/2012 Open hyperlinks in new window/tab/pop-up ?
04/21/2012 PNG transparencies glitched
04/01/2010 Workaround for JSFL shape selection bug?

Flash Cookbooks

More
02/13/2012 Randomize an array
02/11/2012 How to create a Facebook fan page with Flash
02/08/2012 Digital Clock
01/18/2012 Recording webcam video & audio in a flv file on local drive

Products

  • Acrobat
  • Creative Cloud
  • Creative Suite
  • Digital Marketing Suite
  • Digital Publishing Suite
  • Elements
  • Mobile Apps
  • Photoshop
  • Touch Apps
  • Student and Teacher Editions

Solutions

  • Digital marketing
  • Digital media
  • Web Experience Management

Industries

  • Education
  • Financial services
  • Government

Help

  • Product help centers
  • Orders and returns
  • Downloading and installing
  • My Adobe

Learning

  • Adobe Developer Connection
  • Adobe TV
  • Training and certification
  • Forums
  • Design Center

Ways to buy

  • For personal and home office
  • For students, educators, and staff
  • For small and medium businesses
  • For businesses, schools, and government
  • Special offers

Downloads

  • Adobe Reader
  • Adobe Flash Player
  • Adobe AIR
  • Adobe Shockwave Player

Company

  • News room
  • Partner programs
  • Corporate social responsibility
  • Career opportunities
  • Investor Relations
  • Events
  • Legal
  • Security
  • Contact Adobe
Choose your region United States (Change)
Choose your region Close

North America

Europe, Middle East and Africa

Asia Pacific

  • Canada - English
  • Canada - Français
  • Latinoamérica
  • México
  • United States

South America

  • Brasil
  • Africa - English
  • Österreich - Deutsch
  • Belgium - English
  • Belgique - Français
  • België - Nederlands
  • България
  • Hrvatska
  • Česká republika
  • Danmark
  • Eastern Europe - English
  • Eesti
  • Suomi
  • France
  • Deutschland
  • Magyarország
  • Ireland
  • Israel - English
  • ישראל - עברית
  • Italia
  • Latvija
  • Lietuva
  • Luxembourg - Deutsch
  • Luxembourg - English
  • Luxembourg - Français
  • الشرق الأوسط وشمال أفريقيا - اللغة العربية
  • Middle East and North Africa - English
  • Moyen-Orient et Afrique du Nord - Français
  • Nederland
  • Norge
  • Polska
  • Portugal
  • România
  • Россия
  • Srbija
  • Slovensko
  • Slovenija
  • España
  • Sverige
  • Schweiz - Deutsch
  • Suisse - Français
  • Svizzera - Italiano
  • Türkiye
  • Україна
  • United Kingdom
  • Australia
  • 中国
  • 中國香港特別行政區
  • Hong Kong S.A.R. of China
  • India - English
  • 日本
  • 한국
  • New Zealand
  • 台灣

Southeast Asia

  • Includes Indonesia, Malaysia, Philippines, Singapore, Thailand, and Vietnam - English

Copyright © 2012 Adobe Systems Incorporated. All rights reserved.

Terms of Use | Privacy Policy and Cookies (Updated)

Ad Choices

Reviewed by TRUSTe: site privacy statement