Posted By

adrianparr on 01/26/11


Tagged

image red colour color RGB shift bitwise as3 Blue bitmap Green swatch average


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

kure69


AS3 Get Average Colour of an Image


 / Published in: ActionScript 3
 

URL: http://code.google.com/p/sekati/

The docs for the Sekati SWC are here: http://docs.sekati.com/sekati/sekati/utils/ColorUtil.html

Another useful blog post: http://blog.soulwire.co.uk/code/actionscript-3/extract-average-colours-from-bitmapdata

  1. package
  2. {
  3. import flash.display.Bitmap;
  4. import flash.display.Sprite;
  5. import flash.events.Event;
  6. import flash.geom.ColorTransform;
  7.  
  8. import sekati.utils.ColorUtil;
  9.  
  10. public class Main extends Sprite
  11. {
  12.  
  13. [Embed(source="../assets/hero.jpg")]
  14. private var StillImage:Class;
  15.  
  16.  
  17. public function Main():void
  18. {
  19. if (stage) init();
  20. else addEventListener(Event.ADDED_TO_STAGE, init);
  21. }
  22.  
  23. private function init(e:Event = null):void
  24. {
  25. removeEventListener(Event.ADDED_TO_STAGE, init);
  26.  
  27. var image:Bitmap = new StillImage();
  28. addChild(image);
  29.  
  30. var swatch:Sprite = new Sprite();
  31. swatch.graphics.beginFill(0xFF0000);
  32. swatch.graphics.drawRect(0, 0, image.width, 40);
  33. swatch.graphics.endFill();
  34. swatch.x = image.x;
  35. swatch.y = image.y + image.height;
  36. addChild(swatch);
  37.  
  38. var averageRed:int = ColorUtil.averageRed(image);
  39. var averageGreen:int = ColorUtil.averageGreen(image);
  40. var averageBlue:int = ColorUtil.averageBlue(image);
  41.  
  42. var colour:uint = averageRed << 16 | averageGreen << 8 | averageBlue;
  43.  
  44. trace(averageRed + ", " + averageGreen + ", " + averageBlue);
  45.  
  46. var ct:ColorTransform = new ColorTransform();
  47. ct.color = (colour);
  48. swatch.transform.colorTransform = ct;
  49.  
  50. var hexColour:String = "#" + colour.toString(16).toUpperCase();
  51. trace("hexColour: "+hexColour);
  52.  
  53. }
  54.  
  55. }
  56.  
  57. }

Report this snippet  

You need to login to post a comment.