views:

1737

answers:

2

I have an image (mx) and i want to get the uint of the pixel that was clicked.

Any ideas?

+8  A: 

A few minutes on the BitmapData LiveDoc Page will take you where you need to go. Once you have your image loaded into a Bitmap variable, you can access its BitmapData property. Add a Mouse Click Event Listener to the image and then use BitmapData::getPixel. The example for getPixel shows how to convert the uint response to an rgb hex code.

Here's a modification of the Example given on the BitmapData page that worked for me (using mxmlc - YMMV):

package {
    import flash.display.Bitmap;
    import flash.display.BitmapData;
    import flash.display.Loader;
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.MouseEvent;
    import flash.net.URLRequest;

    public class BitmapDataExample extends Sprite {
        private var url:String = "santa-drunk1.jpg";
        private var size:uint = 200;
     private var image:Bitmap;

        public function BitmapDataExample() {
            configureAssets();
        }

        private function configureAssets():void {
            var loader:Loader = new Loader();
            loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);

            var request:URLRequest = new URLRequest(url);
            loader.load(request);
            addChild(loader);
        }

        private function completeHandler(event:Event):void {
            var loader:Loader = Loader(event.target.loader);
            this.image = Bitmap(loader.content);

      this.addEventListener(MouseEvent.CLICK, this.clickListener);
        }

     private function clickListener(event:MouseEvent):void {
      var pixelValue:uint = this.image.bitmapData.getPixel(event.localX, event.localY)
      trace(pixelValue.toString(16));
     }
    }
}
enobrev
+7  A: 

Here's an even simpler implementation. All you do is take a snapshot of the stage using the draw() method of bitmapData, then use getPixel() on the pixel under the mouse. The advantage of this is that you can sample anything that's been drawn to the stage, not just a given bitmap.

import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.events.*;

stage.addEventListener(MouseEvent.CLICK, getColorSample);

function getColorSample(e:MouseEvent):void {
    var bd:BitmapData = new BitmapData(stage.width, stage.height);
    bd.draw(stage);
    var b:Bitmap = new Bitmap(bd);
    trace(b.bitmapData.getPixel(stage.mouseX,stage.mouseX));
}

Hope this is helpfull!

defmeta