Who wins the award for most popular pixel?

From Soulwire, a snippet that gets the average color in an image:

function averageColour( source:BitmapData ):uint {
         var red:Number = 0;
         var green:Number = 0;
         var blue:Number = 0;

         var count:Number = 0;
         var pixel:Number;

         for (var x:int = 0; x < source.width; x++)
            for (var y:int = 0; y < source.height; y++)           {              pixel = source.getPixel(x, y);                     red += pixel >> 16 &amp; 0xFF;
               green += pixel >> 8 &amp; 0xFF;
               blue += pixel &amp; 0xFF;


         red /= count;
         green /= count;
         blue /= count;

         return red << 16 | green << 8 | blue;

Careful not to pass a BitmapData with transparent pixels to this function, because it will see those as black pixels and you will get a much darker color than you wanted.

One Response to “Who wins the award for most popular pixel?”

  1. mcfrei says:

    Actually, you CAN pass bitmap data with transparent pixels to this, if you will create total_alpha variable and add to it accordingly, and in the end divide not by the count, but by total_alpha…
    That’s easy…

Leave a Reply

Your email address will not be published. Required fields are marked *

This blog is kept spam free by WP-SpamFree.

Get Adobe Flash player