Flash Tip collection 11 : Load Image from Local Drive

by YoupSolo
A utility Class to load Images from Local Drive
(right click and use - load image - in the menu)
♥0 | Line 174 | Modified 2015-09-04 05:15:49 | MIT License
play

ActionScript3 source code

/**
 * Copyright YoupSolo ( http://wonderfl.net/user/YoupSolo )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/gzlgL
 */

package
{

    import flash.display.Bitmap;
    import flash.display.DisplayObjectContainer;
    import flash.display.Shape;
    import flash.display.Sprite;
    import flash.events.ErrorEvent;
    import flash.events.Event;
    import flash.text.TextField;
    import flash.text.TextFieldAutoSize;
    import flash.text.TextFormat;
    
    /**
     * ...
     * @author YopSolo
     */

    public class Main extends Sprite 
    {
        private var lil:LocalImageLoader;
        
        public function Main()         
        {
            if (stage) init();
            else addEventListener(Event.ADDED_TO_STAGE, init);
        }       

        /**
         * Init
         * @param    e
         */
        private function init(e:Event = null):void 
        {
            removeEventListener(Event.ADDED_TO_STAGE, init);
            // entry point            

            var bg:Shape = new Shape();
            bg.graphics.beginFill(0x333333);
            bg.graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight);
            bg.cacheAsBitmap = true;
            addChild(bg);           

            run();
        }        

        private function run():void
        {
            buildTextField(this, 'TIP 11 : Right Click to load an Image from local drive', 2, 2);            

            lil = new LocalImageLoader();
            lil.addEventListener(LocalImageLoader.IMAGE_READY, _onImageReady);
            lil.addEventListener(LocalImageLoader.IMAGE_ERROR, _onImageError);
            contextMenu = lil.contextMenuLoad; // add to the menu
        }

        /**
         * Handlers
         * @param    e
         */
        private function _onImageError(e:ErrorEvent):void 
        {
            throw new Error(e.type+" "+e.text);
        }       

        private function _onImageReady(e:Event):void 
        {
            /**
             * use cas 1
             * no resize, you handle have a ref to the bitmap
             */
             
            /*
            var img:Bitmap = lil.image
            img.x = (stage.stageWidth - img.width) >> 1;
            img.y = (stage.stageHeight - img.height) >> 1;
            addChild( img );
            */

            

            /**
             * use case 2
             * automaticaly add the image to a target container
             */
            // lil.target = this;            

            

            /**
             * use case 3
             * same as use case 1, but the image is rescaled, with ratio preservation or not
             */
             
            var img:Bitmap = lil.imageRescale(stage.stageWidth, stage.stageHeight, true);
            img.x = (stage.stageWidth - img.width) >> 1; // center the image
            img.y = (stage.stageHeight - img.height) >> 1;
            addChild( img );
        }        

        /**
         * Helper function to build a textfield
         * @param    doc
         * @param    txt
         * @param    x
         * @param    y
         * @return
         */
        private function buildTextField(doc:DisplayObjectContainer, txt:String, x:int = 0, y:int = 0):TextField
        {
            var fmt:TextFormat = new TextFormat;
            fmt.color = 0xFFFFFF;
            fmt.font = 'Arial'; //(new FONT_HARMONY() as Font).fontName;
            fmt.size = 11; // 8;
            var tf:TextField = new TextField;
            tf.autoSize = TextFieldAutoSize.LEFT;
            tf.opaqueBackground = 0x0; // opaque background allow a perfect font rendering even in StageQuality.LOW mode
            tf.selectable = false;
            //tf.embedFonts = true;
            tf.defaultTextFormat = fmt;
            tf.text = txt;
            tf.x = x;
            tf.y = y;
            
            doc.addChild(tf);           

            return tf;
        }         
    }    
}


    import flash.display.Bitmap;
    import flash.display.BitmapData;
    import flash.display.DisplayObject;
    import flash.display.DisplayObjectContainer;
    import flash.display.Loader;
    import flash.display.StageQuality;
    import flash.events.ContextMenuEvent;
    import flash.events.Event;
    import flash.events.EventDispatcher;
    import flash.events.IOErrorEvent;
    import flash.events.SecurityErrorEvent;
    import flash.net.FileFilter;
    import flash.net.FileReference;
    import flash.ui.ContextMenu;
    import flash.ui.ContextMenuItem;
    

    /**
     * ...
     * @author YopSolo
     */

    class LocalImageLoader extends EventDispatcher
    {

        public static const IMAGE_READY:String = "localimageloader::image_ready";
        public static const IMAGE_ERROR:String = "localimageloader::image_error";

        private var _image:Bitmap;
        private var _contextMenuLoad:ContextMenu;
        private var _fileRef:FileReference;
        private var _imageFilter:FileFilter;
        private var _loader:Loader;
        private var _loadItem:ContextMenuItem;
        private var _target:DisplayObjectContainer;

        public function LocalImageLoader()
        {
            _contextMenuLoad = new ContextMenu();
            _loadItem = new ContextMenuItem("Load Image", true);
            _contextMenuLoad.customItems.push(_loadItem);
            _imageFilter = new FileFilter("Image", "*.jpg;*.gif;*.png");
            _loadItem.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, _onMenuItemSelect);
        }
        
        private function _onMenuItemSelect(e:ContextMenuEvent):void
        {
            _fileRef = new FileReference();
            _fileRef.browse([_imageFilter]);
            _fileRef.addEventListener(Event.SELECT, _onFileSelected);
            _fileRef.addEventListener(IOErrorEvent.IO_ERROR, _onErroEvent);
            _fileRef.addEventListener(SecurityErrorEvent.SECURITY_ERROR, _onErroEvent);            
        }        

        private function _onFileSelected(e:Event):void
        {
            _loadItem.enabled = false;
            _fileRef.load();
            _fileRef.addEventListener(Event.COMPLETE, _onFileLoaded);
        }

        private function _onFileLoaded(e:Event):void
        {
            _fileRef.removeEventListener(Event.SELECT, _onFileSelected);
            _fileRef.removeEventListener(Event.COMPLETE, _onFileLoaded);
            _fileRef.removeEventListener(IOErrorEvent.IO_ERROR, _onErroEvent);
            _fileRef.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, _onErroEvent);

            if (_loader && _loader.content)
            {
                _loader.unloadAndStop(false);
                _image.bitmapData.dispose();
                _image = null;
            }           

            _loader = new Loader();
            _loader.loadBytes(e.target.data);

            _loader.contentLoaderInfo.addEventListener(Event.COMPLETE, _onLoaderComplete);
        }        

        /**
         * Dispatch
         * @param    e
         */       

        private function _onErroEvent(e:Event):void
        {
            this.dispatchEvent(e);
        }       

        private function _onLoaderComplete(e:Event):void
        {
            _image = new Bitmap(new BitmapData(_loader.contentLoaderInfo.width, _loader.contentLoaderInfo.height, true, 0x0));
            _image.bitmapData.drawWithQuality(_loader, null, null, null, null, true, StageQuality.BEST);
            this.dispatchEvent(new Event(IMAGE_READY));
            _loadItem.enabled = true;          

            if (_target)
            {
                _target.addChild(_image);
            }
        }       

        /**
         *
         * @param    pW, desired min width of the image
         * @param    pH, desired min height of the image
         * @param    if true (default) preserve ratio of the image         
         * @return Bitmap
         */       

        public function imageRescale(pW:int, pH:int, preserveRatio:Boolean = true):Bitmap
        {
            _image.width = pW;
            _image.height = pH;

            if (preserveRatio)
            {
                (_image.scaleX < _image.scaleY) ? _image.scaleY = _image.scaleX : _image.scaleX = _image.scaleY;
                (_image.scaleX > _image.scaleY) ? _image.scaleY = _image.scaleX : _image.scaleX = _image.scaleY;
            }            

            return _image;
        }        

        /**
         * get the raw image (bitmap)
         */
        public function get image():Bitmap
        {
            return _image;
        }       

        /**
         * On your App root : this.contextMenu = myLocalImageLoader.contextMenuLoad;
         */
        public function get contextMenuLoad():ContextMenu
        {
            return _contextMenuLoad;
        }       

        /**
         * Get the target DisplayObjectContainer
         */
        public function get target():DisplayObjectContainer
        {
            return _target;
        }        

        /**
         * (optional) when the image is loaded, add it directly in the container
         */

        public function set target(value:DisplayObjectContainer):void
        {
            _target = value;
        }   
    }