但归根结底,我如何将图像转换为 JSON 对象?
谢谢你。
package
{
// See http://www.blooddy.by/en/crypto/
import by.blooddy.crypto.Base64;
import by.blooddy.crypto.image.PNGEncoder;
import by.blooddy.crypto.serialization.JSON;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.DisplayObject;
import flash.display.Loader;
import flash.display.Sprite;
import flash.events.Event;
import flash.net.URLRequest;
public class JsonImage extends Sprite
{
private var _loader : Loader = new Loader;
public function JsonImage(){
// Load an image
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onExternalImgLoaded);
_loader.load(new URLRequest("http://www.google.com/images/srpr/logo4w.png"));
}
protected function onExternalImgLoaded(event:Event):void{
trace("Google logo loaded");
var json : String = encodeImageToJson(_loader.content);
trace("Display from json : \n" + json);
addChild( loadImageFromJson( json ) );
}
// encode an image to Json format
public function encodeImageToJson(image : *) : String
{
var bd : BitmapData;
// Check image type
if(image is BitmapData)
bd = image;
else if(image is Bitmap)
bd = (image as Bitmap).bitmapData;
else if(image is DisplayObject)
{
bd = new BitmapData(DisplayObject(image).width, DisplayObject(image).height, true, 0);
bd.draw(image);
}else
throw new Error ("Invalid image");
// Encode to json
return by.blooddy.crypto.serialization.JSON.encode({
image:
// Convert bytearray to String
Base64.encode(
// Make PNG bytearray from image
PNGEncoder.encode(bd)
)
});
}
// create a loader that will load an image embed in json
public function loadImageFromJson(jsonData : String) : Loader
{
var l : Loader = new Loader;
l.loadBytes(
Base64.decode(
by.blooddy.crypto.serialization.JSON.decode(jsonData)["image"]));
return l;
}
}
}