AIR:如何保存图片到本地
原文地址:
如果你想保存从视频,图表或表格中获取的图片数据到本地,可以使用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);
import mx.graphics.codec.JPEGEncoder;//create a new instance of the encoder, and set the jpeg compression level from 0 to 100var jpgenc:JPEGEncoder = new JPEGEncoder(80);//encode the bitmapdata object and keep the encoded ByteArrayvar imgByteArray:ByteArray = jpgenc.encode(bmpd);
import mx.graphics.codec.JPEGEncoder;//create a new instance of the encodervar pngenc:PNGEncoder = new PNGEncoder();//encode the bitmapdata object and keep the encoded ByteArrayvar imgByteArray:ByteArray = pngenc.encode(bmpd);
//gets a reference to a new empty jpg image file in user desktopvar fl:File = File.desktopDirectory.resolvePath(”snapshot.jpg”);
//gets a reference to a new empty jpg image file in user desktopvar fl:File = File.desktopDirectory.resolvePath(”snapshot.png”);
//Use a FileStream to save the bytearray as bytes to the new filevar 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); }