views:

309

answers:

1

Hello,

Let say I have a BitmapData with different pixels representing an object, and some black pixels around it that I want to remove.

I would like to obtain a new BitmapData, with width and height of the object represented by non-black pixels.

For example, let say I have a BitmapData 400x400px, but the object represented by non-black pixels occupies the rect: x=100, y=100, width=200, height=200. I want to get new BitmapData representing that rect, all black pixels should be removed. Of course, i have no coordinates for that rectangle, i need somehow to make difference between a full black bitmapdata and the original one, and construct a new bitmapdata (different width and height).

Any idea on how to do this please ?

+3  A: 

You can use getColorBoundsRect to find the dimensions of the differently-colored-pixels inside your BitmapData:

//some fake data
var yourBigBmd:BitmapData = new BitmapData( 300, 300, false, 0 );
yourBigBmd.fillRect( new Rectangle( 10, 10, 30, 60 ), 0xFF0000 );
//a little notch
yourBigBmd.fillRect( new Rectangle( 10, 10, 10, 10), 0x00000 );

var blackColor:uint = 0x000000;
var littleBmdBounds:Rectangle = yourBigBmd.getColorBoundsRect( 0xFFFFFF, blackColor, false );
trace( "littleBmdBounds: " + littleBmdBounds );

This will trace littleBmdBounds: (x=10, y=10, w=30, h=60)

Next, we need to copy what's in those bounds into a new BitmapData:

var littleBmd:BitmapData = new BitmapData( littleBmdBounds.width, littleBmdBounds.height, true, 0 );
var mx:Matrix = new Matrix();
mx.translate( -littleBmdBounds.x, -littleBmdBounds.y );
littleBmd.draw( yourBigBmd, mx );

Finally, use threshold to remove any remaining black and make it transparent:

var blackAlphaColor:uint = 0xFF000000;
var transparentColor:uint = 0x00000000;
littleBmd.threshold( littleBmd, littleBmd.rect, littleBmd.rect.topLeft, "==", blackAlphaColor, transparentColor )
jedierikb
Thank you very much, I can see the pattern here so I can adapt it to my needs :)
Adnan Doric