Total Pageviews

Saturday 2 July 2011

Convert an Image to Base64 string and vice versa

import flash.utils.ByteArray;
import flash.display.Loader;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.events.Event; 
import mx.utils.Base64Decoder; //Transform String in a ByteArray.
import mx.utils.Base64Encoder; //Transform ByteArray in a readable string.
import mx.graphics.codec.PNGEncoder; //Encode a BitmapData in a PNG;

//In this case I had a BitmapData in the library
so I took it from there.
var myBMD:BitmapData=new myBitmapData(0,0); 

//Create the ByteArray of myBMD usinf the PNGEncoder.
var myBMDByteArray:ByteArray=(new PNGEncoder).encode(myBMD);

var compStr:String=compress(myBMDByteArray); //Creates String
trace(compStr);

// The loader acts exactly as we were loading an external 
PNG except the fact that we write the ByteArray.
var loader:Loader = new Loader(); 
// In the loadBytes we write the Base64 String of the image.
loader.loadBytes(uncompress(compStr));
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete);

function loadComplete(e:Event):void
{
    var bmp:BitmapData=new BitmapData(loader.width,loader.height,true,0x0);
    bmp.draw(loader);
    addChild(new Bitmap(bmp));
}

// Compress a ByteArray into a Base64 String.
function compress(bytes:ByteArray):String
{
    var enc:Base64Encoder = new Base64Encoder();   
    enc.encodeBytes(bytes);
    return enc.drain().split("\n").join("");
}

// Uncompress a Base64 String into a ByteArray.
function uncompress(str:String):ByteArray
{
    var dec:Base64Decoder = new Base64Decoder();
    dec.decode(str);
    var newByteArr:ByteArray=dec.toByteArray();       
    return newByteArr;
}


4 comments:

  1. I just wanted to thank you. Because this example is the best among others available on Internet and really helped me. :)

    ReplyDelete
  2. I'm not a developer, i always use the free online base64 image converter to encode and decode base64 image.

    ReplyDelete

Microsoft Logo using flexbox and Reactjs

 <!DOCTYPE html> <html> <head>     <script src="https://unpkg.com/react@18/umd/react.development.js" crossori...