Displaying an image saved as a Base64 encoded string in Flex 3
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.
<?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/xAGiAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgsQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2h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jQBGySn/lm/wD3yaQDfJlP/LN/++TQB7Zag/ZYeP4F/lQA9o0LElFJ9xQAvlR/880/75FAB5Uf/PNP++RQAeVH/wA80/75FAB5Uf8AzzT/AL5FMA8qP/nmn/fIoAcBxSA//9k=
View source is enabled in the following example.
Peter deHaan
Peter deHaan currently works for Adobe on the Flex SDK QA team. While not working on Flex, Flash, and ColdFusion applications, Peter enjoys making up bios and writing in 3rd person. Peter's rarely updated blog can be found at blogs.adobe.com/pdehaan/, actionscriptexamples.com, airexamples.com, and coldfusionexamples.com.
-
Add Widgets (Content Sidebar)
This is your Content Sidebar. Edit this content that appears here in the widgets panel by adding or removing widgets in the Content Sidebar area.
23 Responses to Displaying an image saved as a Base64 encoded string in Flex 3
Leave a Reply Cancel reply
-
Categories
- Accordion
- AccordionHeader
- ActionScript
- AddChild
- AdvancedDataGrid
- Alert
- alpha
- Animate
- AnimateProperties
- Application
- Application (Spark)
- ArrayCollection
- BarChart
- baseColor
- beta
- beta1
- beta2
- Bitmap
- Bitmap/BitmapData
- BitmapData
- BitmapFill
- BitmapFill (Spark)
- BitmapGraphic
- BitmapImage
- BitmapImage (Spark)
- BitmapImageResizeMode
- Border (Spark)
- BorderContainer (Spark)
- Box
- BuildInfo
- Button
- Button (Spark)
- ButtonBar
- ButtonBar (Spark)
- ByteArray
- Camera
- Charting
- CheckBox
- CheckBox (Spark)
- ClassFactory
- CollectionEvent
- Color
- ColorPicker
- ColorUtil
- ComboBox
- ComboBoxArrowSkin
- Compiler
- Component
- Component (Spark)
- Configuration
- Container
- ContextMenu
- ContextMenuEvent
- ContextMenuItem
- CSSCondition
- CSSSelector
- CSSStyleDeclaration
- CurrencyFormatter
- CursorManager
- Data Binding
- DataGrid
- DataGrid (Spark)
- DataGridColumn
- Date
- DateBase
- DateChooser
- DateField
- DateFormatter
- Debugging
- DefaultComplexItemRenderer
- DefaultTileListEffect
- DropDownList
- DropDownList (Spark)
- DropDownListButtonSkin
- DropDownListSkin
- DropShadowFilter
- E4X
- Effects
- Ellipse
- EmailValidator
- Embed
- Event
- Fade
- FileFilter
- FileReference
- fill
- Filters
- Flash
- Flash Integration
- FlashVars
- Flex 3 SDK
- Flex Builder
- Flex Builder 3
- Flex SDK
- Flex4
- FLVPlayback
- FocusManager
- FontLookup
- Fonts
- Form
- Form (Spark)
- FormHeading (Spark)
- FormItem
- FormItem (Spark)
- Forms
- FTETextField (Spark)
- FullScreen
- FullScreenEvent
- FxAnimateColor
- FxButtonBar
- FxCheckBox
- FXG
- FxHScrollBar
- FxHSlider
- FxList
- FxNumericStepper
- FxRadioButton
- FxRotate3D
- FxScroller
- FxTextArea
- FxTextInput
- FxToggleButton
- FxVScrollBar
- FxVSlider
- getStyleDeclaration()
- GradientEntry
- Graphic (Spark)
- HBox
- HDividedBox
- HGroup (Spark)
- HorizontalLayout
- HorizontalList
- HSBColor (Spark)
- HScrollBar (Spark)
- HSlider
- HSlider (Spark)
- HTML template
- ID3Info
- Image
- Image (Spark)
- ImageSnapshot
- itemRenderer
- JointStyle
- Label
- Label (Spark)
- Legend
- LegendItem
- LigatureLevel
- Line
- LinearGradientStroke
- LineScaleMode
- LinkBar
- LinkButton
- List
- List (Spark)
- Menu
- MenuBar
- Metadata
- MetadataEvent
- Model
- Mouse
- MouseCursor
- MouseEvent
- Move
- Namespace
- NavigatorContent (Spark)
- needsSWF
- NetConnection
- NetStream
- Nightly Builds
- NumberBaseRoundType
- NumberFormatter
- NumberValidator
- NumericCompare
- NumericStepper
- NumericStepper (Spark)
- ObjectProxy
- ObjectUtil
- paddingLeft
- paddingRight
- Panel
- Panel (Spark)
- Parallel
- Path
- PieChart
- PieSeries
- PieSeriesItem
- PopUpAnchor (Spark)
- PopUpButton
- PopUpManager
- ProgrammaticSkin
- ProgressBar
- PropertyChangeEvent
- QName
- RadialGradient
- RadioButton
- RadioButton (Spark)
- RadioButtonGroup
- RadioButtonGroup (Spark)
- Rect
- RegExp
- Regular Expressions
- Repeater
- RichEditableText
- RichText
- RichText (Spark)
- RichTextEditor
- Rotate
- Rotate3D (Spark)
- Scroller (Spark)
- Sequence
- setStyle()
- SimpleText
- SimpleText (Spark)
- skinClass
- Slider
- SliderEvent
- SolidColor
- SolidColorStroke
- Sort
- SortField
- Sound
- SoundEffect
- Spinner (Spark)
- SpriteVisualElement (Spark)
- StageDisplayState
- States
- StringUtil
- StringValidator
- StyleManager
- Styles
- SWFLoader
- SWFObject
- System
- SystemManager
- TabBar
- TabBar (Spark)
- TabNavigator
- TabStopFormat
- Text
- Text Layout Framework (TLF)
- TextArea
- TextArea (Spark)
- TextBox
- TextConverter
- TextEvent
- TextFlow
- TextFlowUtil
- TextFormat
- TextGraphic
- TextInput
- TextInput (Spark)
- TextLayoutFormat
- TextView
- Themes
- TileLayout
- TileList
- TileOrientation
- Timer
- TitleWindow
- TitleWindow (Spark)
- TLF
- ToggleButton (Spark)
- ToggleButtonBar
- ToolTip
- Transition
- Tree
- TruncationOptions
- UIComponent
- UIFTETextField
- Updater
- URLLoader
- URLRequest
- URLUtil
- URLVariables
- ValidationResultEvent
- Validator
- Validators
- VBox
- VDividedBox
- Vector
- VerticalLayout
- VerticalLayout (Spark)
- VGroup (Spark)
- Video
- VideoDisplay
- VideoElement
- VideoElement (Spark)
- VideoEvent
- VideoPlayer (Spark)
- VideoPlayerScrubBar
- ViewStack
- VScrollBar (Spark)
- VSlider
- VSlider (Spark)
- XML
- XMLList
- XMLListCollection
- ZipCodeValidator
- ZipCodeValidatorDomainType
- Zoom
-
Articles
- December 2010
- November 2010
- October 2010
- September 2010
- August 2010
- July 2010
- June 2010
- May 2010
- April 2010
- March 2010
- February 2010
- January 2010
- December 2009
- November 2009
- October 2009
- September 2009
- August 2009
- July 2009
- June 2009
- May 2009
- April 2009
- March 2009
- February 2009
- January 2009
- December 2008
- November 2008
- October 2008
- September 2008
- August 2008
- July 2008
- June 2008
- May 2008
- April 2008
- March 2008
- February 2008
- January 2008
- December 2007
- November 2007
- October 2007
- September 2007
- August 2007
- July 2007
-
Meta


You are Simply great!!!!
This code is not working, there is no class “Base64Decoder” in mx.utils package :(
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
thanks! it works with flex 3!! it took me hours to find out this solution
this post should put into the flex api document
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…….
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:
Peter
Thank you, this is indeed helpful.
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
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
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
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 thewriteInt()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
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???
Thankyou so much :)
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.
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!
I need put images in a datagridColumn from database whit a xml file:
i use the class Bade64Decoder…
my idea:
any Idea?
sorry
I need put images in a datagridColumn from database whit a xml file:
/9j/4RWrRXh..... .....AAAAAAAAAAAAA==
i use the class Bade64Decoder…
my idea:
I need put images in a datagridColumn from database whit a xml file:
i use the class Bade64Decoder…
my idea:
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
Hi peter , i had used the tilelist so i need the base64 string decoding in image’s source tag..
thanks in advance
Ajith
how do you encode the image to base64? do you have an example?
Man! You’ve just turned on the light bulb over my brain after 2 days struggling with PHP GD library and a bunch of Flex display objects… Thanks.