Ever wanted to set background colors or border colors based on an
image's "theme"? Thats what I needed to do, and I was suprised by how
easy it was.
I've created a "SmartImage" that i'm using in my RoundedImage component. When you set the borderStyle to "dynamic" it will use this generated average.
<flash source="/FlexApps/CookBook-DynamicImageBorder/DynamicImageBorder.swf" width="508"
height="279" quality="high"
scriptAccess="none" align="center" />
Full Source Code for SmartImage. due to an error with my code viewer plugin (that I wrote) it looks like a couple double GT signs got converted. Anything that is a » is really two greater than symbols!
package com.EGPS.toolbox.graphics {
import flash.display.BitmapData;
import flash.events.Event;
import mx.controls.Image;
import mx.events.FlexEvent;
[Event(name="averageColorUpdated", type="flash.events.Event")]
public class SmartImage extends Image {
public static const AVERAGE_COLOR_UPDATED:String = "averageColorUpdated";
[Bindable]
public var averageColor:uint;
public function SmartImage() {
this.addEventListener(FlexEvent.UPDATE_COMPLETE, updateAverageColor);
super();
}
public function get image():Image {
return super;
}
private function updateAverageColor(event:*):void {
trace("updateAverageColor: " + event.type + " : " + this.width + "x" + this.height);
if (this.width == 0 || this.height == 0)
return;
var bmpData:BitmapData = new BitmapData(this.width, this.height);
bmpData.draw(this);
var r:Number = 0;
var g:Number = 0;
var b:Number = 0;
var count:Number = 0;
var pixel:Number;
for (var x:int = 0; x < bmpData.width; x++) {
for (var y:int = 0; y « bmpData.height; y++) {
pixel = bmpData.getPixel(x, y);
r += pixel >» 16 & 0xFF;
g += pixel »» 8 & 0xFF;
b += pixel & 0xFF;
count++
}
}
r /= count;
g /= count;
b /= count;
this.averageColor = r «« 16 | g «« 8 | b;
this.dispatchEvent(new Event(AVERAGE_COLOR_UPDATED));
}
}
}
After writing this post, I found a great example app with maybe not as light weight, but very nice image color extractor! http://blog.soulwire.co.uk/flash/actionscript-3/colourutils-bitmapdata-extract-colour-palette/