核心提示:如果你想保存從視頻,圖表或表格中獲取的圖片數據到本地,可以使用BitmapData類。 原文地址: http://www.adobe.com/cfusion/communityengine/index.cfm?event=showdetails&productId=2&postId=8406 如果你想保存從視頻,圖表或表格中獲取的圖片數據到本地,可以使用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); }