Different Color Averaging algorithms
Based on this blog post: http://asserttrue.blogspot.com/2008/10/fast-pixel-averaging.html
/**
* Copyright Quasimondo ( http://wonderfl.net/user/Quasimondo )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/lvsf
*/
package {
import flash.display.Shape;
import flash.display.Graphics;
import flash.text.TextField;
import flash.display.Sprite;
public class ColorAveraging extends Sprite
{
public function ColorAveraging()
{
var tf:TextField = new TextField();
tf.autoSize = "left";
tf..x = 130;
var shp:Shape = new Shape();
var g:Graphics = shp.graphics;
for ( var i:int = 0; i < 50; i++ )
{
var a:int = Math.random() * 0x1000000;
var b:int = Math.random() * 0x1000000;
g.beginFill( a )
g.drawRect( 16,i*16,16,16 );
g.endFill();
g.beginFill( b )
g.drawRect( 32,i*16,16,16 );
g.endFill();
g.beginFill( avg1(a,b) )
g.drawRect( 60,i*16,16,16 );
g.endFill();
g.beginFill( avg2(a,b) )
g.drawRect( 76,i*16,16,16 );
g.endFill();
g.beginFill( avg3(a,b) )
g.drawRect( 92,i*16,16,16 );
g.endFill();
g.beginFill( avg4(a,b) )
g.drawRect( 108,i*16,16,16 );
g.endFill();
tf.appendText( a.toString(16)+" : "+b.toString(16)+" - "+avg1(a,b).toString(16) + " | "+avg2(a,b).toString(16) + " | "+ avg3(a,b).toString(16) + " | " + avg4(a,b).toString(16) + "\n");
}
addChild(shp);
addChild(tf);
}
private function avg1( a:int, b: uint ):int
{
var REDMASK:int = 0xff0000;
var GREENMASK:int = 0x0000ff00;
var BLUEMASK:int = 0x000000ff;
var aRed:int = a & REDMASK;
var aGreen:int = a & GREENMASK;
var aBlue:int = a & BLUEMASK;
var bRed:int = b & REDMASK;
var bGreen:int = b & GREENMASK;
var bBlue :int= b & BLUEMASK;
var aveRed :int= (aRed + bRed) >> 1;
var aveGreen:int = (aGreen + bGreen) >> 1;
var aveBlue:int = (aBlue + bBlue) >> 1;
return (aveRed & REDMASK ) | (aveGreen & GREENMASK) | ( aveBlue & BLUEMASK );
}
private function avg2( a:int, b:int ):int
{
var MASK7BITS:int = 0xfefeff;
a &= MASK7BITS;
b &= MASK7BITS;
return (a+b)>>1;
}
private function avg3( a:int, b:int ):int
{
var lowbits:int = (((a & 0x7f7f7f) + (b & 0x7f7f7f)) & 0xfefefe)
var highbits:int = (a & 0x808080) + (b & 0x808080);
return (lowbits + highbits) >> 1;
}
private function avg4( a:int, b:int ):int
{
return ( a + b - ((a ^ b) & 0x10101)) >> 1
}
}
}