ActionScript
AIR

[AIR] ローカルに画像保存

More than 5 years have passed since last update.
/**
 * copyright (c) 2012 www.itoz.jp
 * @author itoz
 * @since 2012/06/20 19:55:22
 */
package jp.itoz.air.util
{
    import flash.events.ErrorEvent;
    import flash.filesystem.File;
    import flash.filesystem.FileMode;
    import flash.filesystem.FileStream;
    import flash.utils.ByteArray;
    import flash.events.EventDispatcher;
    import flash.events.IEventDispatcher;

    /**
     * [AIR] ローカルに画像保存
     */
    public class LocalImageSaver extends EventDispatcher
    {
        public function LocalImageSaver(target : IEventDispatcher = null)
        {
            super(target);
        }

        /**
         * 保存
         * @param writeFile
         * @param imageBytes
         */
        public function save(writeFile : File, imageBytes : ByteArray) : void
        {
            var stream : FileStream = new FileStream();
            try {

                stream.open(writeFile, FileMode.WRITE);
                stream.writeBytes(imageBytes, 0, imageBytes.length);

            }
            catch (e : Error) {
                dispatchEvent(new ErrorEvent(ErrorEvent.ERROR, false, false, writeFile + " 保存できませんでした"));
            }
            finally {
            stream.close();
            }
        }
    }
}
//sample
_saveDir = File.userDirectory;
var pngBytes : ByteArray    = PNGEncoder.encode(myBitmapData);
_saver = new LocalImageSaver();
_saver.addEventListener(ErrorEvent.ERROR, onSaveError);
_saver.save(_saveDir.resolvePath("hoge"+"/"+_name), pngBytes);