Image control

Adobe Flex supports several image formats, including GIF, JPEG, and PNG. You can import these images into your applications by using the Spark Image control or BitmapImage. To load SWF files, you use the SWFLoader control.

The Image control is part of both MX and Spark component sets. While you can use the MX Image control in your application, Adobe recommends that you use the Spark Image control instead.

Flex provides the following image controls:

Image control

Use

BimapImage

BitmapImage is a light-weight image control that can load both local and remote assets. You typically use the BitmapImage when you don’t require a broken image icon or a preloader.

The BitmapImage also supports runtime loading of images. However, when you load images at runtime, you should be aware of the security restrictions of Flash Player or AIR. For more information, see Security.

Spark Image

The Spark Image is a skinnable component that leverages a BitmapImage class as its main skin part.

The Spark Image control provides a preloader as well as a broken image icon to indicate an invalid image state. The image loader and the broken-image icon are both customizable. For example, you can provide a broken image icon representing an invalid URL, or provide a progress bar as the image loads. The Spark Image control also provides customizable skinning for borders, frames, and loading states. For more information, see Skinning the Spark Image control.

The Spark Image control lets you load local and trusted assets, as well as remote and untrusted assets. Security restrictions are applicable in case of untrusted assets. For more information, see Loading images using a customizable load interface.

SWFLoader

Flex also includes the SWFLoader control for loading applications built in Flex. You typically use the Image control for loading static graphic files, and use the SWFLoader control for loading SWF files and applications built in Flex. The Image control is also designed for use in custom item renderers and item editors.

For more information on the SWFLoader control, see SWFLoader control.

The following example shows a BitmapImage embedded at compile time and a BitmapImage loaded at runtime:

<?xml version="1.0"?>
<!-- controls\image\ImageBitmapImageExample.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:s="library://ns.adobe.com/flex/spark" 
    xmlns:mx="library://ns.adobe.com/flex/mx"
    width="700">
    
    <s:Panel title="BitmapImage Examples" width="600">
        <s:layout>
            <s:HorizontalLayout horizontalAlign="center"/>
        </s:layout>
        <s:BorderContainer width="50%" height="100%">
            <s:layout>
                <s:VerticalLayout
                   verticalAlign="middle"
                   horizontalAlign="center"/>
            </s:layout>
            <s:Label text="BitmapImage embedded at compile time"/>
            <s:BitmapImage id="embimg" source="@Embed(source='fblogo.jpg')"
               height="50" width="50"/>
        </s:BorderContainer>
        <s:BorderContainer width="50%" height="100%">
            <s:layout>
                <s:VerticalLayout
                   verticalAlign="middle"
                   horizontalAlign="center"/>
            </s:layout>
            <s:Label text="BitmapImage loaded at runtime"/>
            <s:BitmapImage id="runtimeimg" source="../assets/flexlogo.jpg"
               height="50" width="50"/>
        </s:BorderContainer>
    </s:Panel>    
</s:Application>

The executing SWF file for the previous example is shown below:

For a video on using Spark Image and BitmapImage, see www.adobe.com/go/learn_flexsparkimagevideo_en

About loading images

Flex supports loading GIF, JPEG, and PNG files at runtime, and also embedding GIF, JPEG, and PNG files at compile time. The method you choose depends on the file types of your images and your application parameters.

Embedded images load immediately, because they are already part of the Flex SWF file. However, they add to the size of your application and slow down the application initialization process. Embedded images also require you to recompile your applications whenever your image files change. For an overview of resource embedding, see Embedding assets.

The alternative to embedding a resource is to load the resource at runtime. You can load a resource from the local file system in which the SWF file runs. You can also access a remote resource, typically though an HTTP request over a network. These images are independent of your application built with Flex, so you can change them without causing a recompile operation as long as the names of the modified images remain the same. The referenced images add no additional overhead to an application’s initial loading time. However, you can sometimes experience a delay when you use the images and load them into Adobe Flash Player or AIR.

A SWF file can access one type of external resource only, either local or over a network; it cannot access both types. You determine the type of access allowed by the SWF file by using the use-network flag when you compile your application. When use-network flag is set to false, you can access resources in the local file system, but not over the network. The default value is true, which allows you to access resources over the network, but not in the local file system.

For more information on the use-network flag, see Flex compilers.

When you load images at runtime, you should be aware of the security restrictions of Flash Player or AIR. For example, you can reference an image by using a URL, but the default security settings only permit applications built in Flex to access resources stored on the same domain as your application. To access images on other servers, ensure that the domain that you are loading from uses a crossdomain.xml file.

For more information on application security, see Security.

Loading and embedding images with Spark Image and BitmapImage controls

The Spark Image control and BitmapImage support the following actions when you load an image:

Specifying the image path

The value of the source property of a Spark Image control or BitmapImage specifies a relative or absolute path, or URL to the imported image file. If the value is relative, it is relative to the directory that contains the file that uses the tag.

The source property has the following forms:

  1. source="@Embed(source='relativeOrAbsolutePath')"

    The referenced image is packaged within the generated SWF file at compile time when Flex creates the SWF file for your application. You can embed GIF, JPEG, and PNG files. When embedding an image, the value of the source property must be a relative or absolute path to a file on the Flex developer’s local file system; it cannot be a URL.

    The following example embeds a JPEG image into an application that is built in Flex:

    <?xml version="1.0"?>
    <!-- controls\image\ImageSimpleEmbed.mxml -->
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
        xmlns:s="library://ns.adobe.com/flex/spark" 
        xmlns:mx="library://ns.adobe.com/flex/mx">
    
        <s:Image id="loader1" source="@Embed(source='logo.jpg')"/> 
    </s:Application>

    The executing SWF file for the previous example is shown below:

    In this example, the size of the image is the default size of the image file.

  2. source="relativeOrAbsolutePathOrURL"

    Flex loads the referenced image file at runtime, typically from a location that is deployed on a web server; the image is not packaged as part of the generated SWF file. You can only reference GIF, JPEG, and PNG files.

    The following example accesses a JPEG image at runtime:

    <?xml version="1.0"?>
    <!-- controls\image\ImageSimple.mxml -->
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
        xmlns:s="library://ns.adobe.com/flex/spark" 
        xmlns:mx="library://ns.adobe.com/flex/mx">
     
        <s:Image id="loader1" source="assets/flexlogo.jpg"/> 
    </s:Application>

    The executing SWF file for the previous example is shown below:

    Because you did not use @Embed in the source property, Flex loads the image at runtime. In this case, the location is the same directory as the page that embedded the SWF file.

    When the use-network flag is set to false, you can access resources in the local file system, but not over the network. The default value is true, which allows you to access resources over the network, but not in the local file system.

In many applications, you create a directory to hold your application images. Commonly, that directory is a subdirectory of your main application directory. The source property supports relative paths to images, which let you specify the location of an image file relative to your application directory.

The following example stores all images in an assets subdirectory of the application directory:

<?xml version="1.0"?>
<!-- controls\image\ImageSimpleAssetsDir.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:s="library://ns.adobe.com/flex/spark" 
    xmlns:mx="library://ns.adobe.com/flex/mx">

    <s:Image id="loader1" source="@Embed(source='assets/logo.jpg')"/> 
</s:Application>

The executing SWF file for the previous example is shown below:

The following example uses a relative path to reference an image in an assets directory at the same level as the application’s root directory:

<?xml version="1.0"?>
<!-- controls\image\ImageSimpleAssetsDirTop.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:s="library://ns.adobe.com/flex/spark" 
    xmlns:mx="library://ns.adobe.com/flex/mx">

    <s:Image id="loader1" source="@Embed(source='../assets/logo.jpg')"/> 
</s:Application>

The executing SWF file for the previous example is shown below:

You can also reference an image by using a URL, but the default security settings only permit applications to access resources stored on the same domain as your application. To access images on other servers, make sure that the domain that you are loading the image from uses a crossdomain.xml file that allows cross-domain access.

Cross-domain image loading is supported with restrictions. You can load local and trusted assets, as well as remote and untrusted assets. When you use untrusted assets, security restrictions are applicable. When a cross-domain image is loaded from an untrusted source, the security policy does not allow access to the image content. Then, the trustedSource property of the BimapImage and Spark Image is set to false, and the following image properties do not function:

  • BitmapFillMode.REPEAT

  • scaleGrid

  • smooth

  • smoothingQuality

Any advanced operations on the image data, such as, high-quality scaling or tiling, are not supported.

For more information, see Security.

The following example shows how to reference an image by using a URL:

<?xml version="1.0"?>
<!-- controls\image\ImageSimpleAssetsURL.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:s="library://ns.adobe.com/flex/spark" 
    xmlns:mx="library://ns.adobe.com/flex/mx">

    <s:Image id="image1" 
        source="http://localhost:8100/flex/assets/logo.jpg"/> 
</s:Application>
Note: You can use relative URLs for images hosted on the same web server as the application, but load these images over the Internet rather than access them locally.

Using an image multiple times

You can use the same image multiple times in your application by using the normal image import syntax each time. Flex only loads the image once, and then references the loaded image as many times as necessary.

Sizing and scaling an image

You can size and scale images using both the Spark Image and BimapImage controls.

Sizing an image

Flex sets the height and width of an imported image to the height and width settings in the image file. By default, Flex does not resize the image.

To set an explicit height or width for an imported image, set its height and width properties of the image control. Setting the height or width property prevents the parent from resizing it. The scaleContent property has a default value of true; therefore, Flex scales the image as it resizes it to fit the specified height and width. The aspect ratio is maintained by default for a Spark Image, so the image may not completely fill the designated space. Set the scaleContent property to false to disable scaling.

When you resize a BitmapImage, the aspect ratio is not maintained, by default. To ensure that you maintain the aspect ratio, change the value of the scaleMode property from stretch to letterbox or zoom. For more information about image aspect ratios, see below.

One common use for resizing an image is to create image thumbnails. In the following example, the image has an original height and width of 100 by 100 pixels. By specifying a height and width of 20 by 20 pixels, you create a thumbnail of the image.

<?xml version="1.0"?>
<!-- controls\image\ImageSimpleThumbnail.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:s="library://ns.adobe.com/flex/spark" 
    xmlns:mx="library://ns.adobe.com/flex/mx">

    <s:BitmapImage id="image1" 
        source="@Embed(source='logo.jpg')" 
        width="20" height="20"
        smooth="true" smoothingQuality="high"/>
    <s:BitmapImage id="image2" 
        source="@Embed(source='logo.jpg')"/>
</s:Application>

The executing SWF file for the previous example is shown below:

When you downscale a BimapImage, the default quality for scaled bitmaps, BitmapSmoothingQuality.DEFAULT, is used.

If you want to preserve the aspect ratio when creating image thumbnails, and achieve the best quality result when downscaling a BitmapImage, set the smoothingQuality property to BitmapSmoothingQuality.HIGH. The smoothingQuality property is applicable only when you set the smooth property of the BitmaImage to true. When you do so, a multi-bit-rate step algorithm is applied to the image, resulting in a much higher quality downscale than the default. This option is useful in creating high-quality image thumbnails.

To let Flex resize the image as part of laying out your application, set the height and width properties to a percentage value. Flex attempts to resize components with percentage values for these properties to the specified percentage of their parent container. You can also use the maxHeight and maxWidth and minHeight and minWidth properties to limit resizing. For more information on resizing, see Introduction to containers.

Maintaining aspect ratio when sizing

The aspect ratio of an image is the ratio of its width to its height. For example, a standard NTSC television set uses an aspect ratio of 4:3, and an HDTV set uses an aspect ratio of 16:9. A computer monitor with a resolution of 640 by 480 pixels also has an aspect ratio of 4:3. A square has an aspect ratio of 1:1.

All images have an inherent aspect ratio. When you use the height and width properties of the Image control to resize an image, Flex preserves the aspect ratio of the image, by default, so that it does not appear distorted.

By preserving the aspect ratio of the image, Flex might not draw the image to fill the entire height and width specified for the <s:Image> tag. For example, if your original image is a square 100 by 100 pixels, which means it has an aspect ratio of 1:1, and you use the following statement to load the image:

<s:Image source="myImage.jpg" height="200" width="200"/>

The image increases to four times its original size and fills the entire 200 x 200 pixel area.

The following example sets the height and width of the same image to 150 by 200 pixels, an aspect ratio of 3:4:

<s:Image source="myImage.jpg" height="150" width="200"/>

In this example, you do not specify a square area for the resized image. Flex maintains the aspect ratio of a Spark Image by default because the scaleMode property is set to letterbox. Therefore, Flex sizes the image to 150 by 150 pixels, the largest possible image that maintains the aspect ratio and conforms to the size constraints. The other 50 by 150 pixels remain empty. However, the <s:Image> tag reserves the empty pixels and makes them unavailable to other controls and layout elements.

To ensure that you maintain the aspect ratio when you resize a BitmapImage, change the value of the scaleMode property from stretch to letterbox or zoom.

When you resize an image, you can apply the required alignment properties. The Spark Image and BitmapImage both have horizontalAlign and verticalAlign properties that you can specify, as required.

By default, the horizontalAlign and verticalAlign properties are set to center. For example, when you resize an image that has an original height and width of 1024 by 768 to a height and width of 100 by 100, there is extra space at the top and bottom of the image. You can set the the horizontalAlign and verticalAlign properties as required to overcome the extra space.

You can also use a Resize effect to change the width and height of an image in response to a trigger. As part of configuring the Resize effect, you specify a new height and width for the image. Flex maintains the aspect ratio of the image by default, so it resizes the image as much as possible to conform to the new size, while maintaining the aspect ratio. For example, place your pointer over the image in this example to enlarge it, and then move the mouse off the image to shrink it to its original size:

<?xml version="1.0"?>
<!-- controls\image\ImageResize.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:s="library://ns.adobe.com/flex/spark" 
    xmlns:mx="library://ns.adobe.com/flex/mx">
    <fx:Script>
        <![CDATA[
            import mx.effects.Resize;
        ]]>
    </fx:Script>
    <fx:Declarations>
        <s:Resize id="resizeBig" 
            widthFrom="22" widthTo="44" 
            heightFrom="27" heightTo="54"/>
        <s:Resize id="resizeSmall" 
            widthFrom="44" widthTo="22" 
            heightFrom="54" heightTo="27"/>
    </fx:Declarations>

    <s:Image width="22" height="27"
        source="@Embed('logo.jpg')" 
        rollOverEffect="{resizeBig}" 
        rollOutEffect="{resizeSmall}"/>
        
</s:Application>

The executing SWF file for the previous example is shown below:

For more information on the Resize effect, see Introduction to effects.

Scaling images using fillMode and scaleMode properties

You use the fillMode image property to determine how an image fills into a region.

You can use the fillMode property in a tag or in ActionScript, and set one of the following values:

  • scale: scales the image to fill the bounding region.

  • clip: displays the image in its original size. If the image is larger than the bounding region, the image is clipped to the size of the bounding region. If the image is smaller than the bounding region, an empty space is left.

  • repeat: repeats or tiles the image and fills into the dimensions of the bounding region.

When you set the fillMode property to scale , you can set the scaleMode property to stretch, letterbox, or zoom.

When you use the fillMode property in ActionScript, you use BitmapFillMode.CLIP, BitmapFillMode.REPEAT, or BitmapFillMode.SCALE.

To stretch the image content to fit the bounding region, set the attribute value to BitmapScaleMode.STRETCH. If you set the value to BitmapScaleMode.LETTERBOX, the image content is sized to fit the region boundaries while maintaining the same aspect ratio as the original unscaled image. For BitmapScaleMode.ZOOM, the image content is scaled to fit with respect to the original unscaled image's aspect ratio. This results in cropping along one axis.

The following example shows the Flex logo scaled in the letterbox-mode and stretch-mode using the fillMode and scaleMode properties:

<?xml version="1.0"?>
<!-- controls\image\ImageScaling.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
               xmlns:s="library://ns.adobe.com/flex/spark" 
               xmlns:mx="library://ns.adobe.com/flex/mx">
    
    <s:controlBarContent>
        <s:Form>
            <s:FormItem label="scaleMode:">
                <s:DropDownList id="ddl" selectedItem="letterbox">
                    <s:dataProvider>
                        <s:ArrayList source="[letterbox,scale]" />
                    </s:dataProvider>
                </s:DropDownList>
            </s:FormItem>
        </s:Form>
    </s:controlBarContent>
    
    <s:Image id="image"
       source="assets/flexlogo.jpg"
       height="20" width="20"
       fillMode="scale"
       scaleMode="{ddl.selectedItem}"
       left="20" right="20" top="20" bottom="20" />
</s:Application>

The executing SWF file for the previous example is shown below:

For more code examples, see Peter deHaan's blog.

Skinning the Spark Image control

The Spark Image control lets you customize the appearance of you image through skinning.

When you use the <s:Image> tag to import an image, a default skin class, ImageSkin, is created. The default skin provides a simple image skin that has a content loader with a generic progress bar and a broken image icon to reflect invalid content.

The ImageSkin class provides Spark and wireframe-themed skins that let you customize the content loader and the icon to identify images that failed to load. You also have customizable skinning for borders, frames, and loading states.

The ImageSkin class defines the following optional skin parts:

  • imageDisplay:BitmapImage: Lets you specify the image to display for invalid content or loading error.

  • ProgressIndicator:Range: Lets you specify the range, maximum, and minimum values of the progress bar. Use the stepSize property to specify the amount by which the value changes when the changeValueByStep() method is called.

For information about the different skin states, see the source code for the ImageSkin class.

For examples on customizing skins and icons for the Spark Image control, see Peter deHann’s blog post.

Caching and queuing of images

The ContentCache class supports caching and queuing of remote image assets, and can be associated with the BitmapImage or Spark Image controls.

You set the caching and queuing properties for the image content loader as follows:

<fx:Declarations> 
    <s:ContentCache id="imgcache" enableCaching="true" enableQueueing="true" 
    maxActiveRequests="1" maxCacheEntries="10"/> 
</fx:Declarations>

To have a content loader with only queuing capabilities and no caching capabilities, set enableCaching to false.

The difference that you notice in image-loading when you use the caching-queuing mechanism can be significant, especially with large images. Without caching, large images can take several seconds to load. For example, you can use caching and queuing to prevent image-flickering in a scrolling list.

The ContentCache class provides the following methods and properties to manage caching and queuing:

Caching properties

Property name

Description

maxCacheEntries

Specifies the number of cache entries that can be stored at a given time. When the cache entries exceed the specified number, the least recent cache entries are automatically removed. The default value is 100.

enableQueuing

Enables queuing of images. The default value is false.

enableCaching

Enables caching of images. The default value is true.

maxActiveRequests

Specifies the number of pending load requests that can be active at a given time when image-queuing is enabled. The default value is 2.

Caching methods

Method name

Description

load()

Returns the requested image using the ContentRequest instance. If the image is still loading, ContentRequest returns a value of false. If the requested image is found in the cache, ContentRequest returns a value of complete.

removeAllCacheEntries()

removeCacheEntry()

Removes cache entries.

Use removeCacheEntry() to remove a single cache entry that's no longer needed. Use removeAllCacheEntries() to remove all the cached content.

getCacheEntry()

Checks for a pre-existing cache entry, and if found, obtains a reference to the cache entry.

addCacheEntry()

Adds a new cache entry. Use addCacheEntry to manually add a cache entry.

Queuing methods

Method

Description

prioritize()

Forces all pending requests of the specified contentLoaderGrouping to be moved to the top of the request list, when image-queuing is enabled. Any active URL requests at that time are canceled and requeued if their contentLoaderGrouping does not match the prioritized content grouping.

removeAllQueueEntries()

Cancels all the queued requests.

Example on caching and queuing images

The following example shows loading of images using the contentLoader. Caching and queuing are enabled and custom item renderers are used.

<?xml version="1.0"?>
<!-- controls\image\ImageCaching.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:s="library://ns.adobe.com/flex/spark" 
    xmlns:mx="library://ns.adobe.com/flex/mx">
    
    <fx:Style>
        @namespace s "library://ns.adobe.com/flex/spark";
        @namespace mx "library://ns.adobe.com/flex/mx";
        
        s|Image {
            enableLoadingState: true;
        }
    </fx:Style>
    
    <fx:Script>
        <![CDATA[
            import mx.collections.ArrayList;
            
            protected var arrList:ArrayList = new ArrayList();
            
            protected function init():void {
                var rand:String = new Date().time.toString()
                var arr:Array = [];
                arr.push({src:"http://localhost:8100/flex/assets/fblogo.jpg?" + rand, cache:ldr});
                arr.push({src:"http://localhost:8100/flex/assets/flexlogo.jpg?" + rand, cache:ldr});
                
                arrList = new ArrayList(arr);
                dataGrp.dataProvider = arrList;
            }
        ]]>
    </fx:Script>
    
    <fx:Declarations>
        <s:ContentCache id="ldr" enableQueueing="true"
           maxActiveRequests="1" maxCacheEntries="10"/>
    </fx:Declarations>
    
    <s:Panel title="Loading images using the caching-queuing mechanism" x="20" y="20">
        <s:controlBarContent>
            <s:Button label="Load Images" click="init();"/>
        </s:controlBarContent>
        <s:DataGroup id="dataGrp">
            <s:layout>
                <s:TileLayout />
            </s:layout>
            <s:itemRenderer>
                <fx:Component>
                    <s:ItemRenderer dataChange="imageDisplay.source = data.src;">
                        <s:Image id="imageDisplay" contentLoaderGrouping="gr1"
                           contentLoader="{data.cache}" width="200" height="200" />
                    </s:ItemRenderer>
                </fx:Component>
            </s:itemRenderer>
        </s:DataGroup>
    </s:Panel>    
</s:Application>
Note: You can replace the URLs in the example to access images over the Internet rather than access them locally.

Loading images using a customizable load interface

Flex provides a customizable content loader, IContentLoader, to load images. The IContentLoader has a simple interface that contains a load method to manage the load requests. For a given source, which is usually a URL, the load method returns the requested resources using the ContentRequestinstance. The ContentRequest instance provides the load progress information and also notifies any content validation errors.

The load method also provides a contentLoaderGrouping instance to manage multiple load requests as a group. For example, the ContentCache's queuing methods allows requests to be prioritized by contentLoaderGrouping.