2025-02-09

如果你想保存從視頻,圖表或表格中獲取的圖片數據到本地,可以使用BitmapData類。

摘要:

使用BitmapData類來創建一個包含瞭從組件中獲取的圖片數據的對象,使用mx.graphics.codec包提供的方法編碼為JPEG或PNG格式,然後使用AIR API提供的File和FileStream類保存到本地。

具體方法:

首先我們我們需要得到屏幕的截圖,要做到這一點,我們要使用BitmapData類。比如我們想從一個命名為myChart的線狀圖表上獲取截圖:
Java代碼 
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格式:
Java代碼 
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格式:
Java代碼 
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文件參照:
Java代碼 
//gets a reference to a new empty jpg image file in user desktop 
var fl:File = File.desktopDirectory.resolvePath(”snapshot.jpg”); 

AIR:如何保存圖片到本地建立一個PNG文件參照:
Java代碼 
//gets a reference to a new empty jpg image file in user desktop 
var fl:File = File.desktopDirectory.resolvePath(”snapshot.png”); 

現在我們可以把ByteArray用File Stream保存到文件中。
Java代碼 
//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); 
   } 

作者“Jack-Chen”
 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *