0

I have a whole bunch of jpg files that I need to use in a project, that for one reason or another cannot be altered. Each file is similar (handwriting), black pen on white BG. However I need to use these assets against a non-white background in my flash project, so I'm trying to do some client-side processing to get rid of the backgrounds using getPixel and setPixel32.

The code I am currently using currently uses a linear comparison, and while it works, the results are less than expected, as the shades of grey are getting lost in the mix. Moreso than just tweaking my parameters to get things looking proper, I get the feeling that my method for computing the RGBa value is weak.

Can anyone recommend a better solution than what I'm using below? Much appreciated!

private function transparify(data:BitmapData) : Bitmap {

    // Create a new BitmapData with transparency to return
    var newData:BitmapData = new BitmapData(data.width, data.height, true);
    var orig_color:uint;
    var alpha:Number;
    var percent:Number;

    // Iterate through each pixel using nested for loop
    for(var x:int = 0; x < data.width; x++){
        for (var y:int = 0; y < data.height; y++){

            orig_color = data.getPixel(x,y);

            // percent is the opacity percentage, white should be 0, 
            // black would be 1, greys somewhere in the middle
            percent = (0xFFFFFF - orig_color)/0xFFFFFF;

            // To get the alpha value, I multiply 256 possible values by 
            // my percentage, which gets multiplied by 0xFFFFFF to fit in the right
            // value for the alpha channel
            alpha = Math.round(( percent )*256)*0xFFFFFF;

// Adding the alpha value to the original color should give me the same 
// color with an alpha channel added
            var newCol = orig_color+alpha;
            newData.setPixel32(x,y,newCol);
        }
    }

    var newImg:Bitmap = new Bitmap(newData);
    return newImg;
} 
Conor
  • 670
  • 1
  • 12
  • 27

1 Answers1

0

Since it's a white background, blendMode may give you a better result.

PatrickS
  • 9,539
  • 2
  • 27
  • 31
  • BlendMode.MULTIPLY did exactly what I wanted it to do. Unfortunatly I found this out after modifying my code above to produce the exact same result. The trick was using bitwise operators instead of what I was using above. That being said, I'm accepting your answer as a filter is probably less intensive than scanning each pixel and creating a new bitmap for each image. – Conor Nov 12 '10 at 20:13