使用 BitmapData 來做影像翻轉

2008/03/19

水平翻轉:將最上列的像素與最下列的像素做交換, 將第二列的像素與最下列的像素做交換, 將第三列...., 一直做到中間列。
垂直翻轉:做法同上,只是改成最左欄與最右欄交換。

private function getImageBitmapData(image: Image):BitmapData
{
var bd:BitmapData = Bitmap(image.content).bitmapData;
return bd;
} 

水平翻轉
private function horizontalFlip(event:MouseEvent):void {
var bitmapData:BitmapData = getImageBitmapData(img);

var rect:Rectangle = new Rectangle(0, 0, bitmapData.width, bitmapData.height);
var data:ByteArray = bitmapData.getPixels(rect);

var width:int = bitmapData.width;
var height:int = bitmapData.height;
var arr:Array = new Array(width * height * 4);

data.position = 0;
for(var y:int = 0; y < height; y++) {
for(var x:int = width - 1; x >= 0; x--) {
var val:int = data.readInt();
var pos:int = (y * width * 4) + (x * 4);
arr[pos + 0] = (val & 0xFF000000) >> 24;
arr[pos + 1] = (val & 0x00FF0000) >> 16; //data.readByte();
arr[pos + 2] = (val & 0x0000FF00) >>  8; //data.readByte();
arr[pos + 3] = (val & 0x000000FF); //data.readByte();
}
}

var b:ByteArray = new ByteArray();
for(var j:int = 0; j < data.length; j++) {
b.writeByte(arr[j]);
}

b.position = 0;
bitmapData.setPixels(rect, b);
}

垂直翻轉
private function verticalFlip(event:MouseEvent):void {   
var bitmapData:BitmapData = getImageBitmapData(img);

var rect:Rectangle = new Rectangle(0, 0, bitmapData.width, bitmapData.height);
var data:ByteArray = bitmapData.getPixels(rect);

var width:int = bitmapData.width;
var height:int = bitmapData.height;
var arr:Array = new Array(width * height * 4);

data.position = 0;
for(var y:int = height - 1; y >= 0; y--) {
for(var x:int = 0; x < width; x++) {
var val:int = data.readInt();
var pos:int = (y * width + x) << 2; //在迴圈中,使用 shift 運算子來提升運算效率。
arr[pos + 0] = (val & 0xFF000000) >> 24;
arr[pos + 1] = (val & 0x00FF0000) >> 16; //data.readByte();
arr[pos + 2] = (val & 0x0000FF00) >>  8; //data.readByte();
arr[pos + 3] = (val & 0x000000FF); //data.readByte();
}
}

var b:ByteArray = new ByteArray();
for(var j:int = 0; j < data.length; j++) {
b.writeByte(arr[j]);
}

b.position = 0;
bitmapData.setPixels(rect, b);
} 


0 意見:

程式 . 生活 . D小調.@2010 | Binary Design: One Winged Angel.