当前位置 :主页>知识堂>AIR教程>列表

AIR:如何保存图片到本地

时间:2008-04-29 来源:www.52ria.com  作者:浪迹天涯   点击:
    核心提示:如果你想保存从视频,图表或表格中获取的图片数据到本地,可以使用BitmapData类。

原文地址:

Save a local image file (JPEG or PNG) from an image snapshot

如果你想保存从视频,图表或表格中获取的图片数据到本地,可以使用BitmapData类。

摘要:

使用BitmapData类来创建一个包含了从组件中获取的图片数据的对象,使用mx.graphics.codec包提供的方法编码为JPEG或PNG格式,然后使用AIR API提供的File和FileStream类保存到本地。

具体方法:

首先我们我们需要得到屏幕的截图,要做到这一点,我们要使用BitmapData类。比如我们想从一个命名为myChart的线状图表上获取截图:

import flash.display.BitmapData;
var bmpd:BitmapData = new BitmapData(myChart.width,myChart.height);
bmpd.draw(myChart);

然后我们需要把bitmapdata对象编译为ByteArray对象,这样我们就可以保存为文件了。这个ByteArray对象需要被格式化,我们可以使用mx.graphics.codec包中的JPEGEncoder和PNGEncoder类来实现它。

编码为JPEG格式:

import mx.graphics.codec.JPEGEncoder;
//create a new instance of the encoder, and set the jpeg compression level from 0 to 100
var jpgenc:JPEGEncoder = new JPEGEncoder(80);
//encode the bitmapdata object and keep the encoded ByteArray
var imgByteArray:ByteArray = jpgenc.encode(bmpd);

编码为PNG格式:

import mx.graphics.codec.JPEGEncoder;
//create a new instance of the encoder
var pngenc:PNGEncoder = new PNGEncoder();
//encode the bitmapdata object and keep the encoded ByteArray
var imgByteArray:ByteArray = pngenc.encode(bmpd);

现在我们已经准备好了ByteArray数据,我们只需要把它保存到本地就可以了。我们可以用File和File Stream类来实现。

建立一个JPEG文件参照:

//gets a reference to a new empty jpg image file in user desktop
var fl:File = File.desktopDirectory.resolvePath(”snapshot.jpg”);

建立一个PNG文件参照:

//gets a reference to a new empty jpg image file in user desktop
var fl:File = File.desktopDirectory.resolvePath(”snapshot.png”);

现在我们可以把ByteArray用File Stream保存到文件中。

//Use a FileStream to save the bytearray as bytes to the new file
var fs:FileStream = new FileStream();
try{
//open file in write mode
fs.open(fl,FileMode.WRITE);
//write bytes from the byte array
fs.writeBytes(imgByteArray);
//close the file
fs.close();
}catch(e:Error){
trace(e.message);
}

参加以下的示例:

Sample applications
save_img.zip

上一篇:AIR TIP5:在安装过程中传递参数     下一篇:[翻译]AIR TIP4:调用SOAP Webservice
版权申明:除部分特别声明不要转载,或者授权我站独家播发的文章外,大家可以自由转载我站点的原创文章,但原作者和来自我站的链接必须保留(非我站原创的,按照原来自一节,自行链接)。文章版权归我站和作者共有。
转载要求:转载之图片、文件,链接请不要盗链到本站,且不准打上各自站点的水印,亦不能抹去我站点水印。
特别注意:本站所提供的源文件,电子书,第三软件,如需使用,请与原作者联系,版权归原作者所有,文章若有侵犯作者版权,请与我们联系,我们将立即删除修改。
 评论内容:(最新评论共有 0) 位网友发表了评论不能超过250字,需审核,请自觉遵守互联网相关政策法规。
用户名: 密码: 匿名? 马上注册
 
 
知识堂分类
 
本站所提供的所有素材版权归原作者所有,本站只供网友参考与交流,未经作者同意请勿用于商业用途
服务器带宽提供:零刻数据 本站CDN由海诺互动提供技术支持。 下载带宽支持:重庆万网
京ICP备08051668号