Search code examples
actionscript-3bitmapalpha-transparency

Remove Whitepixels from a bitmap


I converted a movieclip with a lot of unused space into a bitmap, but it seems alike that many white pixels have been added to the bitmap during the conversion so the background wont be displayed properly.

My question is how to remove the background the smartest way... remove every single white pixel and if so how to do it? generate a alphamap from the movieclip if possible how to? or some other way that I dont know about?

thx in advance =)


Solution

  • refer a following code. this code is if pixel is white color, convert to transparent color.

    for(var i:int = 0; i<myBitmapData.width; i++)
    {
        for(var j:int = 0; j<myBitmapData.height; j++)
        {
            if(myBitmapData.getPixel(i,j) == 0xffffff)
            {
                var transparent:uint = 0x00000000;
                myBitmapData.setPixel32(i, j, transparent);
            }
        }
    }
    

    you've checked following code. before tested, must stage of change the color to Red or Blue or Green... you want.

    import flash.display.Sprite;
    import flash.events.Event;
    import flash.display.BitmapData;
    import flash.display.Bitmap;
    import flash.events.MouseEvent;
    
    var brush:Sprite =new Sprite();
    brush.graphics.beginFill(0xffffff);
    brush.graphics.drawRect(0,0,100,100);
    brush.graphics.endFill();
    //addChild(brush);
    
    var myBitmap:Bitmap = new Bitmap(convertToBitmap(brush));
    var bmd:BitmapData = myBitmap.bitmapData;
    addChild(myBitmap);
    
    for(var i:int = 0; i<bmd.width; i++)
    {
        for(var j:int = 0; j<bmd.height; j++)
        {
            if(bmd.getPixel(i,j) == 0xffffff)
            {
                var transparent_color:uint = 0x00000000;
                bmd.setPixel32(i, j, transparent_color);
            }
        }
    }
    
    function convertToBitmap( clip:DisplayObject ):BitmapData
    {
        var bounds:Rectangle = clip.getBounds( clip );
        var bitmap:BitmapData = new BitmapData( int( bounds.width + 0.5 ), int( bounds.height + 0.5 ), true, 0 );
        bitmap.draw( clip, new Matrix(1,0,0,1,-bounds.x,-bounds.y) );
        return bitmap;
    }