2007年8月8日 星期三

用 BitmapData.paletteMap 轉 256 色

好多 BitmapData 的函式第一次用,試作了一個 [ 轉 256 色 ] 與 [ 指定範圍的 Pixel 值 ] 的功能。




import flash.display.BitmapData;
import flash.geom.Matrix;
import flash.geom.Point;
import flash.geom.Rectangle;
//----------------------------------取得WEB216安全色的BitmapData
function get256bd(srcBD:BitmapData):BitmapData{
var safeColorArray:Array = [0x00, 0x33, 0x66, 0x99, 0xCC, 0xFF];

var redArray:Array = new Array(256);
var greenArray:Array = new Array(256);
var blueArray:Array = new Array(256);

for(var i:Number = 0; i < 256; i++) {
var c:Number = i;
for(j=0; j<safeColorArray.length; j++){
if(c <= safeColorArray[j]){
c = safeColorArray[j];
break;
}
}
redArray[i] = c << 16;
greenArray[i] = c << 8;
blueArray[i] = c;
}

var rect:Rectangle = new Rectangle(0, 0, srcBD.width, srcBD.height);
var pt:Point = new Point(0, 0);
var bd = new BitmapData(srcBD.width, srcBD.height, true, 0x00000000);
bd.paletteMap(srcBD, rect, pt, redArray, greenArray, blueArray);

return bd;
}
//----------------------------------由指定範圍取出一個像素值
function getPixelByRect(sourceBD:BitmapData, rect:Rectangle):Number{
var rectBD:BitmapData = new BitmapData(rect.width, rect.height, true, 0x00000000);
rectBD.copyPixels(sourceBD, rect, new Point(0, 0));

var bd1Pixel:BitmapData = new BitmapData(1, 1, true, 0x00000000);
var matrix:Matrix = new Matrix();
matrix.scale(1/rect.width, 1/rect.height);
bd1Pixel.draw(rectBD, matrix);
return bd1Pixel.getPixel32(0, 0);
}
//----------------------------------載入圖檔
var _mcl:MovieClipLoader = new MovieClipLoader();
var _mclListener:Object = {};
_mclListener.onLoadInit = function(target_mc:MovieClip){
//trace(target_mc._width + ", " + target_mc._height);

var bd:BitmapData = new BitmapData(target_mc._width, target_mc._height, true, 0x00000000);
bd.draw(target_mc);

//取得WEB216安全色的BitmapData
bd = get256bd(bd);

var img256_mc:MovieClip = _root.createEmptyMovieClip("img256_mc", _root.getNextHighestDepth());
img256_mc.attachBitmap(bd, 2);
img256_mc._x = 100;

//----------

var bd2:BitmapData = new BitmapData(target_mc._width, target_mc._height, true, 0x00000000);

var cols:Number = 20;
var rows:Number = 20;
var cubeWidth:Number = target_mc._width / cols;
var cubeHeight:Number = target_mc._height / rows;
for(var i:Number=0; i<cols; i++){
for(var j:Number=0; j<rows; j++){
var rect:Rectangle = new Rectangle(cubeWidth*i, cubeHeight*j, cubeWidth, cubeHeight);
//由指定範圍取出一個像素值
var color:Number = getPixelByRect(bd, rect);
bd2.fillRect(rect, color);
}
}

var img2_mc:MovieClip = _root.createEmptyMovieClip("img2_mc", _root.getNextHighestDepth());
img2_mc.attachBitmap(bd2, 2);
img2_mc._x = 200;

}
_mcl.addListener(_mclListener);

var oraImg_mc:MovieClip = _root.createEmptyMovieClip("oraImg_mc", _root.getNextHighestDepth());
_mcl.loadClip("D:\\photos\\photo.jpg", oraImg_mc);

沒有留言: