Search code examples
imageactionscript-3cropbitmapdatathreshold

Flash AS3 get bitmapdata region without transparent pixels


I have a pictures of goods. There is a white border around some images. White color is not uniform and has some shades (poor quality etc.). I need to cut this border. To remove white color I use:

bd.threshold(bd, rect, pt, ">", threshold, color, maskColor);

There are some none transparent pixels after threshold because threshold color is unique for every image. BitmapData.getColorBoundsRect return region include none transparent pixels. I need region without this pixels(only image). Check each pixel is bad for big pictures. What is the most economical way to do this(find green region on picture below)? Sorry for my bad english and thanks for any help.

image crop example


Solution

  • There are four edges of the image: left, right, top, down. Check each of them starting from the edge and moving towards inside of the image.

    For example, let's take top edge (y = 0).

    1. choose any horisontal position in the edge, for example, x = 10.
    2. check pixel at (x, y).
    3. if it is transparent, move the edge down: y++;
    4. goto 2 and repeat until the pixel is not transparent.
    5. choose different horisontal position and goto 2.

    Repeat several times with different x. If there are only occasional non-transparent pixels, repeating the process 5-10 times will give you a new top edge which will most probably be 100% precise. It doesn't matter if the image is big, you only check several places in the edge. Do the same for left, right and bottom edges. Then copy the image defined by these edges.

    If the edge quality is really bad then it's better to edit all images manually.