Powered By Blogger

Saturday, December 22, 2012

Flex: Displayable Image from an Image Resource

  Following is a class which can be used to convert and an image resource (here a png file) to a displayable image (mx.controls.Image) instance in Flex. Here a static function 'displayableImageFromClass(Image, int, int): void ' does the work. The function's height and width parameters are optional and they specify the height and width of the displayable image that is returned.

================================================================

package com.shyarmal.drawing.utils {
    import flash.display.Bitmap;
    import flash.display.BitmapData;
    import flash.utils.ByteArray;
   
    import mx.controls.Image;
    import mx.graphics.codec.PNGEncoder;
   

    public class ImageUtils {
       
        /**
         * png image encoder.
         */
        private static var encoder:PNGEncoder = new PNGEncoder();
       
        public function ImageUtils() {
        }
       
        /**
         * Given a class (with an embeded png image), 
         * creates a corresponding displayable image,
         * if imageClass is not null.
         *
         * @param imageClass - The image class from 
         *            which the image has to be created.
         * @param height - Height of the final image (optional).
         * @param width - Width of the final image (optional).
         * @return - mx.controls.Image produced.
         */
        public static function displayableImageFromClass( 
                   imageClass: Class, height: int = 25, 
                                   width: int = 25): Image {
            var i:Image = new Image();
            if (imageClass != null) {
                var bitMap: Bitmap = new imageClass();
                var bitmapData: BitmapData = bitMap.bitmapData;
                bitmapData.draw(bitMap);
                var imageToDisplay:ByteArray = 
                         encoder.encode(bitmapData);
                i.source = imageToDisplay;
                i.height = height;
                i.width = width;
            }
            return i;
        }
    }
}

================================================================

  If the 'imageClass' parameter is null, simply a new instance of mx.controls.Image is formed and returned. If not a 'Bitmap' is formed by instantiating the 'imageClass' passed in. Then its 'BitmapData' is derived. A byte array is constructed with the help of PNGEncoder and assigned to the source of the image instance. Image is returned after setting its dimensions.

Invocation of the method can be done as below;

[Embed (source="/assets/images/your_png.png" )] 
var resource: Class; // define a class with the actual resource.

// height and width can be passed if necessary.
var i:Image = ImageUtils.displayableImageFromClas(resource);



thanks,
Shyarmal.

No comments:

Post a Comment