Flash (AS3): Reading Image From Database Blob Field
Software, Technology October 20th, 2008
Scenario:
- You have no write access to a deployment server, thus you have to save user-uploaded image to a Blob field in a database. Sad, but it happens.
- You need to read this photo entry in Flash, trying to stream it in and it shows nothing but gibberish.
- You might think that setting
header("Content-type");server side would work but IT DOESN’T.
Solution: Base 64 Encoding / Decoding
Note: I’m gonna use PHP server side scripting for this example
- Before saving the image data to the Blob field,
base64_encode()the file stream. Say… you call this scriptsaveimage.php - Extract out the file from the server using normal query procedure, spit it out using
echo. This would be yourfetchimage.php - Follow up with this AS3 script
Declare your variables
//variable declarations stuff
private var avatarString:String;
private var bitLoader:Loader;
private var containerImg:MovieClip;
Load the server response
var imgLoader:URLLoader = new URLLoader();
imgLoader.dataFormat = URLLoaderDataFormat.TEXT;
imgLoader.load(new URLRequest("https://www.domain.com/fetchimage.php?id=12345"));
imgLoader.addEventListener(Event.COMPLETE, onDataLoad);
Handle data load
function onDataLoad(evt:Event){
avatarString = evt.target.data.toString();
var decodedString:String = Base64.Decode(avatarString);
var imageBytes:ByteArray = new ByteArray();
for(var i:Number=0; i < decodedString.length ; i++){
imageBytes.writeByte(decodedString.charCodeAt(i));
}
And display it…
bitLoader = new Loader();
bitLoader.loadBytes(imageBytes);
containerImg.addChildAt(bitLoader,0);


