从AS3中的BitmapData获取ByteArray

时间:2014-12-12 13:21:30

标签: actionscript-3 bytearray bitmapdata

我想从AS3中的BitmapData获取ByteArray。我尝试了以下方法:

var ba:ByteArray = myBitmapData.getPixels(0,0);

它没有用,我收到了这个错误ArgumentError: Error #1063: Argument count mismatch on flash.display::BitmapData/getPixels(). Expected 1, got 2.

2 个答案:

答案 0 :(得分:1)

正如Adobe所说BitmapData.getPixels:“从像素数据的矩形区域生成一个字节数组... ”,因此您的参数应为Rectangle object。< / p>

从Adobe.com获取此示例:

import flash.display.BitmapData;
import flash.geom.Rectangle;
import flash.utils.ByteArray;

var bmd:BitmapData = new BitmapData(80, 40, true);
var seed:int = int(Math.random() * int.MAX_VALUE);
bmd.noise(seed);

var bounds:Rectangle = new Rectangle(0, 0, bmd.width, bmd.height);
var pixels:ByteArray = bmd.getPixels(bounds);

答案 1 :(得分:1)

正如在另一个答案中提到的,getpixels期望.rect意味着某些displayObject的矩形区域(如Sprite,MovieClip,Shape或其他已经存在的BitmapData。)

getPixels(). Expected 1, got 2.原因应该是:

var ba:ByteArray = myBitmapData.getPixels( myBitmapData.rect);

研究此代码,看看它是否对您有所帮助:

import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.events.Event;
import flash.net.URLRequest;
import flash.display.BitmapData;

var ba:ByteArray = new ByteArray;

var picBMP:Bitmap; var picBMD:BitmapData; 
var pic_canvas:Sprite = new Sprite(); //container for image

var loader:Loader = new Loader(); //image loader

loader.load(new URLRequest("pic1.jpg")); //load some JPG/PNG/GIF/SWF
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, img_load_Complete);

function img_load_Complete(evt:Event):void
{
    picBMP = loader.content as Bitmap;
    pic_canvas.addChild(picBMP);

    stage.addChild(pic_canvas); //container now added to stage (screen)

    BMP_toBytes(); //do function to convert to bytes
}

function BMP_toBytes():void
{
    var PC = pic_canvas; //shortcut reference to pic_canvas (less typing)

    picBMD = new BitmapData(PC.width, PC.height, true, 0xFFFFFF);
    picBMD.draw(PC); //make bitmapdata snapshot of container

    ba = picBMD.getPixels(picBMD.rect);
    trace("BA length : " + ba.length); //check how many bytes in there

    ba.position = 0; //reset position to avoid "End of File error"

    bytes_toPixels(); //do function for bytes as pixels to some new container
}


function bytes_toPixels():void
{
    var new_BMP:Bitmap = new Bitmap; var new_BMD:BitmapData; 
    var new_canvas:Sprite = new Sprite(); //another new container for pixels

    ba.position = 0; //reset position to avoid "End of File error"

    //we can reuse picBMD W/H sizes since we have copy of same pixels
    new_BMD = new BitmapData(picBMD.width, picBMD.height, true, 0xFFFFFFFF);
    new_BMD.setPixels(new_BMD.rect, ba); //paste from BA bytes
    new_BMP.bitmapData = new_BMD; //update Bitmap to hold new data

    new_canvas.x = 150; new_canvas.y = 0; new_canvas.addChild(new_BMP);
    stage.addChild(new_canvas); //add to screen
}

希望有所帮助......