views:

502

answers:

2

So, I've got this code:

import flash.display.BitmapData;
import flash.display.Bitmap;
import flash.geom.Rectangle;
import flash.utils.ByteArray;

var bmd:BitmapData = new BitmapData(10, 10, true);
var seed:int = int(Math.random() * int.MAX_VALUE);
bmd.noise(seed);

var bounds:Rectangle = new Rectangle(0, 0, bmd.width, bmd.height);
var pixels:ByteArray = bmd.getPixels(bounds);

Is there a way to get, efficiently and quickly, the dominant color and/or the average color in pixels ByteArray.

noise is used for the example here. I'll be having something else drawn on that BitmapData instead.

I found some ways to extract the average color palate from a BitmapData, but this isn't enough for me since I want the average from a rect over that image.

Thanks in advance!

+3  A: 

the average color is easy, just resize the bitmapData by draw()ing it in to a 1x1 bitmap, flash will average the color in the copy process.

var m: Matrix = new Matrix();
m.scale( 1 / bmd.width, 1 / bmd.height);
var averageColorBmd:BitmapData = new BitmapData(1, 1);
averageColorBmd.draw(bmd, m);
var averageColor:uint = averageColorBmd.getPixel(0,0);

something like that

hth (first answer on this site :-)

Hudson
Nice trick. You could restrict that to a rectangle by creating a new BitmapData for the subimage and copying in the pixels (BitmapData.copyPixels).
Michael Brewer-Davis
+1 Thanks for this suggestion! I think that it will be processing-intensive though. I was looking for somehow "quicker" solution, not requiring some redraw process...
Makram Saleh
actually, draw is extremely optimized since it is part of the flash rendering engine. I don't think you will find anything faster that takes every pixel into account.
Hudson
I guess you are right when it comes to large areas of pixels. In my particular case I have small 10x10 areas, and I just want to check an existence of a color inside that box, so I found that it's enough that I read getPixel info of the mid pixel. Thanks anyway!
Makram Saleh
+1  A: 

FYI this actually does not average or pick the dominant color.

doing it this way is relying on flash to shrink the image down to one pixel and then decide which color to use. I'm not sure how this color is chosen, but through tests it is NOT the average NOR is it the dominant color.

jared
I agree. When i need to do this i usually shrink it down to a 3x3 image and take the middle pixel. The results are often much better
Antti
Thanks for the suggestion! This sounds good too.
Makram Saleh