Displaying an image saved as a Base64 encoded string in Flex 3

by Peter deHaan on March 17, 2008

in Base64Decoder, Image

In a previous example, “Using the ImageSnapshot class to capture images as JPEGs or PNGs in Flex 3″, we saw how you could convert an item on the display list into a base64 encoded string.

The following example shows how you can take a base64 encoded string and load it into a Flex Image control using the decode() and toByteArray() methods in the mx.utils.Base64Decoder class, and the load() method in the mx.controls.Image class.

Full code after the jump.

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/03/17/displaying-an-image-saved-as-a-base64-encoded-string-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.utils.Base64Decoder;

            private var base64Dec:Base64Decoder;

            private function init():void {
                var byteArr:ByteArray;

                base64Dec = new Base64Decoder();
                base64Dec.decode(logo);

                byteArr = base64Dec.toByteArray();

                img.load(byteArr);
            }
        ]]>
    </mx:Script>

    <mx:String id="logo" source="logo.txt" />

    <mx:Form width="100%" height="100%">
        <mx:FormItem label="image:">
            <mx:Image id="img" />
        </mx:FormItem>
        <mx:FormItem label="source:"
                width="100%"
                height="100%">
            <mx:TextArea id="textArea"
                    text="{logo}"
                    editable="false"
                    width="100%"
                    height="100%" />
        </mx:FormItem>
    </mx:Form>

</mx:Application>

/src/logo.txt

/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2MBERISGBUYLxoaL2NCOEJjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY//AABEIADIAMgMBEQACEQEDEQH/xAGiAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgsQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGh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U70Ae12v8Ax6w/7i/yoA8w8UK//CR3uEYjf2HsKYGXtk/55v8AkaAArJ/zzb8jQAwrJ/zzf8jQBGySn/lm/wD3yaQDfJlP/LN/++TQB7Zag/ZYeP4F/lQA9o0LElFJ9xQAvlR/880/75FAB5Uf/PNP++RQAeVH/wA80/75FAB5Uf8AzzT/AL5FMA8qP/nmn/fIoAcBxSA//9k=

View source is enabled in the following example.

{ 20 comments… read them below or add one }

1 Tony March 18, 2008 at 4:57 am

You are Simply great!!!!

Reply

2 Tony March 18, 2008 at 5:33 am

This code is not working, there is no class “Base64Decoder” in mx.utils package :(

Reply

3 peterd March 18, 2008 at 7:49 am

Tony,

Are you using Flex 3? I believe I compiled this using Flex 3.0.0.477 (the retail Flex 3 SDK)

It is in Flex 3: http://livedocs.adobe.com/flex/3/langref/mx/utils/Base64Decoder.html
But not Flex 2: http://livedocs.adobe.com/flex/201/langref/mx/utils/package-detail.html

Peter

Reply

4 David H April 25, 2008 at 12:09 am

thanks! it works with flex 3!! it took me hours to find out this solution
this post should put into the flex api document

Reply

5 anoop May 12, 2008 at 6:42 am

base64Eec = new Base64Eecoder();

There shows one more error 4 me like thaat:call to a possibly undefined method Base64Eecoder

my code is…..

public function postData():void {
var request:HTTPService = new HTTPService();
var base64Eec:Base64Encoder;
request.url = "http://twitter.com/statuses/update.xml";
request.method = "POST";
request.addEventListener(ResultEvent.RESULT,
handleComplete);
var username:String = "username";
var password:String = "password";
 base64Eec = new Base64Eecoder();
 base64Eec.encode(username + ":" + password);
var encodedCredentials:String = base64Eec.toString();
var headerArray = new Array(
new URLRequestHeader("Authentication",
"Basic " + encodedCredentials));

can u help me please…….

Reply

6 peterd May 12, 2008 at 7:28 am

anoop,

Are you using Flex 3? This class was added in Flex 3, and isn’t available in Flex 2 projects.
Also, make sure you’ve imported the Base64Encoder/Base64Decoder class as well:

import mx.utils.Base64Decoder;
import mx.utils.Base64Encoder;

Peter

Reply

7 Magnus May 24, 2008 at 11:39 am

Thank you, this is indeed helpful.

Reply

8 Richard Tolley July 18, 2008 at 5:05 am

First things first – superb blog – would be lost without it. Thank you.

I’m working on some code at the moment and need to display a Base64 String as an image. Used the example above and it worked first time. Thank you.

*BUT* (isn’t there always a but…)

What to do when the String is coming from a database and sometimes contains invalid data.

I thought it would be a simple matter to trap the error and display an alternative image.

Nothing seems to work.

I’ve tried try/catch blocks. I’ve tried using ioError event on the image component.

I’m going out of my mind – Could you suggest a way to trap invalid data. If I can trap the error I can deal with it. Nothing seems to work.

Kind Regards

Once again – the blog is superb :)

Rich

Reply

9 Dustin July 24, 2008 at 1:48 pm

Thanks for the info on this! It saved my butt.

I had been trying to figure out how to create Power Point presentations from Flex and ColdFusion, and this was the trick.

By encoding the images, I am able to embed the images into a .MHT file (which is basically xml), and Power Point can read this file and display the images, just like a ppt file. I even named the file with a .ppt extension so Power Point is the default app to open it, and its all working great.

cheers!
Dustin

Reply

10 ken larkin August 15, 2008 at 6:27 am

thanks this worked. However I am receiving an image as a byte array in a string not base64hex in a string. Data in string looks like this…34,645,234,653,122,12,32,43,543,…

Ho do i convert this string of numbers to a bytearray and in turn into an image

By the way this is a magnificent site, well done.

thanks,
Ken

Reply

11 peterd August 15, 2008 at 7:20 am

ken larkin,

I don’t know if this would work, but you could try converting the list of numbers into an array using the split() method, then loop over the array of numbers and add them to a ByteArray using the writeInt() method. Something like this:

private function stringToByteArray(value:String):ByteArray {
	var arr:Array = value.split(",");
	var idx:uint;
	var len:uint = arr.length;
	var byteArr:ByteArray = new ByteArray();
	for (idx=0; idx<len; idx++) {
		byteArr.writeInt(arr[idx]);
	}
	return byteArr;
}

But I’m sure there may be a few missing pieces. You could try asking on the FlexCoders mailing list, I’m sure somebody there has attemped what you’re trying to do.

Peter

Reply

12 Suvendu October 24, 2008 at 8:18 am

Hi There,

Very Nice article.just wanted a little help.

I have an array containing the bytearrays of the images .How can i display the images in an horizontal scroll bar.

Can you please help me in this???

Reply

13 Waqas February 12, 2009 at 3:00 am

Thankyou so much :)

Reply

14 lixz April 12, 2009 at 7:02 am

hi there. thanks for the articles. however, i combined some of articles in this sites, so i can preview an image that browsed from FileReference and convert it into Bitmap.

http://ficforlife.com/2009/04/flex-how-to-create-bitmap-from.html

hope that will useful, thank you very much.

Reply

15 passeyhead May 28, 2009 at 9:39 am

Very nice. I was looking for an example of how to stream image data from a PHP script to the Image component. This works very nice. Thanks a heap!

Reply

16 juan September 8, 2009 at 12:44 am

I need put images in a datagridColumn from database whit a xml file:
i use the class Bade64Decoder…

my idea:

 

any Idea?

Reply

17 juan September 8, 2009 at 12:46 am

sorry

Reply

18 juan September 8, 2009 at 12:52 am

I need put images in a datagridColumn from database whit a xml file:

/9j/4RWrRXh..... .....AAAAAAAAAAAAA==

i use the class Bade64Decoder…

my idea:

Reply

19 juan September 8, 2009 at 12:54 am

I need put images in a datagridColumn from database whit a xml file:

 
 
	/9j/4RWrRXh..... .....AAAAAAAAAAAAA==

i use the class Bade64Decoder…

my idea:

 

Reply

20 Joe Wazen January 26, 2010 at 9:43 am

Hello,

my image is saved in a db table in a field of type image :

the data (jpeg format) looks like
0xFFD8FFE000104A4649460001010100C000C00000FFDB004300080606070………..

i am retrieving the data as a string, how cn i display this image?

thnks

Reply

Leave a Comment

Sorry, this blog is terrible at eating HTML comments.
If you're pasting any HTML/XML/MXML code, you need to convert your < characters to &lt; and your > characters to &gt; .

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Anti-Spam Protection by WP-SpamFree

Previous post:

Next post: