正文
[ActionScript3.0] 运用JPEGEncoderOptions或者PNGEncoderOptions保存图片到本地
小程序:扫一扫查出行
【扫一扫了解最新限行尾号】
复制小程序
【扫一扫了解最新限行尾号】
复制小程序
在flash player 11.3和air3.3之前,我们可以借助第三方类(JPEGEncoder)这些,很容易处理。现在,有了encode和JPEGEncoderOptions这些,处理位图数据就更简单快捷了。
flash.display.BitmapData.encode() 方法允许您将位图数据本机压缩为以下图像压缩格式之一:
PNG - 使用 PNG 压缩,可以选择使用快速压缩,它强调的是压缩速度而不是文件大小。若要使用 PNG 压缩,请将新的 flash.display.PNGEncoderOptions 对象作为 BitmapData.encode() 方法的第二个参数传递。
JPEG - 使用 JPEG 压缩,可以选择指定图像品质。若要使用 JPEG 压缩,请将新的 flash.display.JPEGEncoderOptions 对象作为 BitmapData.encode() 方法的第二个参数传递。
JPEGXR - 使用 JPEG 扩展范围 (XR) 压缩,可以选择指定颜色通道、损耗和熵 (entropy) 编码设置。若要使用 JPEGXR 压缩,请将新的 flash.display.JPEGXREncoderOptions 对象作为BitmapData.encode() 方法的第二个参数传递。
您可以将图像处理的此功能用作服务器上传或下载工作流程的一部分。
下面的示例代码片段使用 JPEGEncoderOptions 压缩 BitmapData 对象:
var bitmapData:BitmapData = new BitmapData(640,480,false,0x00FF00);
var byteArray:ByteArray = new ByteArray();
bitmapData.encode(new Rectangle(0,0,640,480), new flash.display.JPEGEncoderOptions(), byteArray);
对于JPEGEncoderOptions的参数,其值介于1和100之间。值为1的时候,品质最低,100品质最高。默认值是80,这个时候,处理出来的位图质量已经很好了。
import flash.net.FileReference;
import flash.utils.ByteArray;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.JPEGEncoderOptions;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.system.Security;
import flash.geom.Rectangle;var _fileRefer:FileReference = new FileReference();
var _byteArr:ByteArray = new ByteArray();
function save():void
{
var rect:Rectangle = new Rectangle(0,0,724,640);
var bmpd:BitmapData = new BitmapData(rect.width,rect.height,true,0); bmpd.draw(_图片容器);
var jpegEncoder:JPEGEncoderOptions = new JPEGEncoderOptions(80);
bmpd.encode(bmpd.rect,jpegEncoder,_byteArr); if (_byteArr != null)
{
var date:Date = new Date();
var str:String = date.fullYear.toString() + (date.month + 1).toString() + date.date.toString() + date.hours + date.minutes + date.seconds + ".jpg";
if (Security.sandboxType.toString() == "application")
{
var file:File = File.userDirectory.resolvePath(str);
var filestream:FileStream = new FileStream();
filestream.openAsync(file, FileMode.WRITE);
filestream.writeBytes(_bytearr);
AlertPanel.getInstance().show("图片保存成功,保存地址:\n"+file.nativePath,true,stage);
trace(file.nativePath);
}
else
{
_fileRefer.save(_byteArr,str);
}
}}