当前位置: 动力学知识库 > 问答 > 编程问答 >

actionscript 3 - Detect and Erase specific pixels from an image

问题描述:

Is it possible to detect (dynamically) the white pixels of an image and delete them? Actually i have some images that i load on stage but they are square without the actual image be a square sized. So i want to make the hit area exactly the shape of the image and not the whit border they have.

ps: In actionscript :)

网友答案:

You can loop through the bitmap data, check each pixel and see if its colour matches the white border but may run into trouble if there are other white pixels in the image, unless you only check certain positions on the image and really this is starting to sound very messy.

EDIT: From what I understand you have images with white borders along the outside and you do not want the borders to be part of the hitarea. What I propose is that you edit the images (externally in photoshop) and remove the white borders.

Then instead recreate these white borders as a seperate image with ActionScript. It would not be too hard to check the size of the actual image and then create a sprite a bit bigger and fill it with white. Then place the actual image on top of it and centered. So now it looks like the image has a border. You can place both the white fill image and the actual image in a container to make it easy to move them as one. You can also easily set the image to be the hitarea and not the border.

网友答案:

You could do it by looping through the pixels, 1 at a time starting from top-left, and bottom-right till you find a non-white pixel. Sort of like this...

First use getPixel

var j:Number = 0;
var i:Number = 0;
var tl_corner:Point; // top left corner
var br_corner:Point; // bottom right corner

for (j = 0; j < imageBitmapData.height; j++) {
    for (i = 0; i < imageBitmapData.width; i++) {
        if (imageBitmapData.getPixel(i, j) != 0xFFFFFF) {
            tl_corner = new Point(i, j)
        }
    }
}


for (j = imageBitmapData.height - 1; j >= 0; j--) {
    for (i = imageBitmapData.width - 1; i >= 0; i--) {
        if (imageBitmapData.getPixel(i, j) != 0xFFFFFF) {
            br_corner = new Point(i, j)
        }
    }
}

Now you have the top left and bottom right corners of the actual image, without the white.

Now use copyPixels

var bmd:BitmapData = new BitmapData(br_corner.x - tl_corner.x, br_corner.y - tl_corner.y, false, 0x00000000);
bmd.copyPixels(imageBitmapData, new Rectangle(tl_corner.x, tl_corner.y, (br_corner.x - tl_corder.y), (br_corner.y - tl_corner.y)), new Point(0, 0));

Now you have a BitmapData object with only the pixels you want. Do with it as you please, maybe:

var s:Sprite = new Sprite();
var bmp:Bitmap = new Bitmap(bmd);
s.addChild(bmp);
分享给朋友:
您可能感兴趣的文章:
随机阅读: