啊,抱歉,我以为你只是想加载图像;我没看到你也想保存它。
对于以下两种情况,您都需要将图像加载为二进制:
var urlLoader:URLLoader = new URLLoader(new URLRequest( myURL ));
urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
...
这是因为如果我们正常加载它(使用Loader),那么我们将得到一个Bitmap 对象,即Flash 的图像表示,而不是jpg/png 数据本身。使用此方法加载它会在加载时为您提供ByteArray。
如果您使用的是 AIR,您应该可以使用 FileStream 类:http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/filesystem/FileStream.html
类似:
// NOTE: you can use any of the other File constants to get your path (e.g.
// documentsDirectory, desktopDirectory...
// myImageFileName is the name of your image, e.g. "myPic.jpg"
var file:File = File.applicationStorageDirectory.resolvePath( myImageFileName );
var fs:FileStream = new FileStream;
try
{
fs.open( file, FileMode.WRITE );
fs.writeBytes( imageBinaryData ); // imageBinaryData is a ByteArray
fs.close();
}
catch ( e:Error )
{
trace( "Can't save image: " + e.errorID + ": " + e.name + ": " + e.message );
}
如果您使用的是 Flash,那么无需用户交互即可保存内容的唯一方法是通过SharedObject。这意味着您的数据将无法在应用程序之外使用(它将是一个.sol 文件),但根据您的操作方式,这可能不是问题。
// get our shared object - if you're saving a lot of images, then you might need another shared
// object, whose name you know, that stores the names of the other images
var so:SharedObject = null;
try { so = SharedObject.getLocal( this.m_name ); }
catch ( e:Error )
{
trace( "Couldn't get shared object: " + e.errorID + ": " + e.name + ": " + e.message );
return;
}
// NOTE: it's possible you may need a registerClassAlias on the ByteArray before this
so.data["image"] = imageBinaryData;
// save the lso
try { so.flush( minDiskSpace ); }
catch ( e:Error )
{
trace( "Couldn't save the lso: " + e.errorID + ": " + e.name + ": " + e.message );
}
以后要实际使用您的图像,请加载您的文件(以二进制模式)/获取您的SharedObject,并将保存的二进制文件转换为图像:
var l:Loader = new Loader;
l.contentLoaderInfo.addEventListener( Event.COMPLETE, this._onConvertComplete ); // you could probably also listen for the IO_ERROR event
try
{
// NOTE: you can pass a LoaderContext to the loadBytes methods
l.loadBytes( imageBinaryData );
}
catch( e:Error )
{
trace( "Couldn't convert image: " + e.errorID + ": " + e.name + ": " + e.message );
}
...
// called when our loader has finished converting our image
private function _onConvertComplete( e:Event ):void
{
// remove the event listeners
var loaderInfo:LoaderInfo = ( e.target as LoaderInfo );
loaderInfo.removeEventListener( Event.COMPLETE, this._onConvertComplete );
// get our image
var bitmap:Bitmap = loaderInfo.content;
this.addChild( bitmap );
}
如果您不能使用这些方法中的任何一种,那么您将不得不进行某种用户交互(例如鼠标单击)。 (出于好奇,您是否尝试过在相关对象上分派MouseEvent.CLICK,看看它是否可行?)