Setting a default encoder for the ImageSnapshot class in Flex 3

The following example shows how you can set the ImageSnapshot class’s static defaultEncoder property in Flex 3 to set a default image encoder for captured images.

Full code after the jump.

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2007/12/08/setting-a-default-encoder-for-the-imagesnapshot-class-in-flex-3/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white"
        creationComplete="init();">

    <mx:Script>
        <![CDATA[
            import mx.graphics.ImageSnapshot;
            import mx.graphics.codec.*;

            private function init():void {
                ImageSnapshot.defaultEncoder = PNGEncoder;
            }

            private function captureImg():void {
                var ohSnap:ImageSnapshot = ImageSnapshot.captureImage(img);
                textArea.text = ImageSnapshot.encodeImageAsBase64(ohSnap);
                lbl.text = ohSnap.contentType;
            }
        ]]>
    </mx:Script>

    <mx:ApplicationControlBar dock="true">
        <mx:Button id="button"
                label="Capture Image"
                click="captureImg();" />
    </mx:ApplicationControlBar>

    <mx:Form>
        <mx:FormItem label="source:">
            <mx:Image id="img"
                    source="@Embed('images/flex_logo.jpg')" />
        </mx:FormItem>
        <mx:FormItem label="Base64:">
            <mx:TextArea id="textArea"
                    editable="false"
                    width="320"
                    height="160" />
        </mx:FormItem>
        <mx:FormItem label="contentType:">
            <mx:Label id="lbl" />
        </mx:FormItem>
    </mx:Form>

</mx:Application>

View source is enabled in the following example.

6 thoughts on “Setting a default encoder for the ImageSnapshot class in Flex 3

  1. OK, Peter. Now what? What can I do with this string? Must I pass it to my server to save it as a file? Can I copy and paste the string into a empty text document and make it a PNG?

    I love your site, btw. I stopped tagging pages and just use it as a reference whenever I run into problems or when I have trouble getting a feature started.

  2. Hi Peter, thanks for the great article, altough I have the same question as Leif.
    What do you do with the String?

    Thanks for the great site! It’s one of the most useful resources on the web.

  3. Kim,

    I haven’t tried it, but I imagine you’d have to send the base64 encoded string to a server side script (ColdFusion, PHP, ASP, etc) which saves it to the server disk. Then you could have the user download the PNG file from the server using the FileReference class’s download() method.

    Peter

Comments are closed.