In case Flash no longer exists; a copy of this site is included in the Flashpoint archive's "ultimate" collection.

Dead Code Preservation :: Archived AS3 works from wonderfl.net

picasaから取得した画像をzip圧縮してローカルPCに保存

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

/*
picasaから検索でヒットする画像を取得し、zipでローカルpcに保存する。
管理用のxmlも同梱する。


【参考】Picasa Web Albums Data API
http://code.google.com/intl/ja/apis/picasaweb/docs/2.0/reference.html
*/
package {
    import com.bit101.components.InputText;
    import flash.display.Bitmap;
    import flash.display.BitmapData;
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.MouseEvent;
    import flash.filters.DropShadowFilter;
    import flash.geom.Matrix;
    import flash.net.FileReference;
    import flash.system.LoaderContext;
    import flash.system.Security;
    import flash.utils.ByteArray;
    import nochump.util.zip.ZipEntry;
    import nochump.util.zip.ZipOutput;
    import com.bit101.components.*;
    import com.adobe.serialization.json.JSONDecoder;
    
    public class Main extends Sprite {
        private var _mulitiLoader:MultiLoader;
        private var _query:InputText;
        private var _urlArea:Text;
        private var _maxResults:NumericStepper;
        private var _imgmax:ComboBox;
        public function Main() {
            //bit101の日本語対応
            Style.embedFonts = false;
            Style.fontName = "_typewriter";
            Style.fontSize = 11;

            _query = new InputText(this, 0, 4, "green", update);
            _query.width = 200;
            
            _maxResults = new NumericStepper(this, 210, 4, update);
            _maxResults.minimum = 1;
            _maxResults.value = 3;
            
            _imgmax = new ComboBox(this, 300, 4);
            var items:Array = [94, 110, 128, 200, 220, 288, 320, 400, 512, 576, 640, 720, 800, 912, 1024, 1152, 1280, 1440, 1600];
            var n:int = items.length;
            for (var i:int = 0; i < n; i++) {
                _imgmax.addItem( { label:String(items[i]) } );
            }
            _imgmax.selectedIndex = 4;
            _imgmax.addEventListener(MouseEvent.MOUSE_UP, update);
            
            _urlArea = new Text(this, 0, 30);
            _urlArea.width = 465;
            _urlArea.height = 60;
            new PushButton(this, 0, 100, "Load", onLoad);
            
            update(null);
        }
        private function update(e:Event):void {
            var str:String = "http://photos.googleapis.com/data/feed/base/all?alt=json&kind=photo";
            str += "&imgor=landscape";
            str += "&imglic=commercial";
            str += "&q=" + encodeURI(_query.text);
            str += "&max-results=" + _maxResults.value;
            str += "&imgmax=" + _imgmax.selectedItem.label;
            _urlArea.text = str;
        }
        
        private function onLoad(e:Event):void {
            //var xmlURL:String = "http://photos.googleapis.com/data/feed/base/all?imgor=landscape&alt=rss&kind=photo&q=waterdrop&imglic=commercial&max-results=30&imgmax=220";
            var xmlURL:String = _urlArea.text;
            //crossdomain.xml(クロスドメインポリシーファイル)の位置を指定
            Security.loadPolicyFile("http://photos.googleapis.com/data/crossdomain.xml");        //*1
            
            _mulitiLoader = new MultiLoader();
            _mulitiLoader.addEventListener(MultiLoader.COMPLETE, onCompleteXML);
            _mulitiLoader.add(xmlURL, { type:"text", id:"xml"} );
            _mulitiLoader.start();
            
        }
        
        private function onCompleteXML(e:Event):void {
            
            var decoder:JSONDecoder = new JSONDecoder(e.target.data);
            var json:Object = decoder.getValue();
           
            var myLoaderContext:LoaderContext = new LoaderContext(true);        //*8
            
            _mulitiLoader.addEventListener(MultiLoader.COMPLETE, onCompleteImg);
            var n:int = json.feed.entry.length;
            for (var i:int = 0; i < n; i++) {
                var url:String = json.feed.entry[i]["media$group"]["media$content"][0].url;
                _mulitiLoader.add(url, { type:"binary", id:"jpg" + i, context:myLoaderContext } );
                var crdt:String = json.feed.entry[i]["media$group"]["media$credit"][0]["$t"];
                var fileName:String = url.substr(url.lastIndexOf("/")+1);
                itemList["jpg" + i] = { credit:crdt, name:fileName };
            }
            
            _mulitiLoader.start();
        }
        private var itemList:Object = { };
        private var _zipOut:ZipOutput;
        private function onCompleteImg(e:Event):void {
            var i:int = 0;
            var n:int = _mulitiLoader.itemsTotal - 1;
            
            
            //zip化
            _zipOut = new ZipOutput();
            
            var xmlString:String = '<?xml version="1.0" encoding="utf-8" ?>\n';
            xmlString += "<data>\n\t<files>\n";
            
            var nums:Array = [];
            for (i = 0; i < n; i++) {
                //zipファイルの生成
                var byteArray:ByteArray = _mulitiLoader.getBinary("jpg" + i);
                try{
                    _zipOut.putNextEntry(new ZipEntry(itemList["jpg" + i].name));
                    _zipOut.write(byteArray);
                    _zipOut.closeEntry();
                }catch (e:*) {
                    //ファイル名が同じ場合、処理できないので
                    trace("*****", i, itemList["jpg" + i].name);
                    continue;
                }
                //info.xmlの内容
                xmlString += "\t\t<file>\n";
                xmlString += "\t\t\t<id>img" + nums.length + "</id>\n";
                xmlString += "\t\t\t<type>image</type>\n";
                xmlString += "\t\t\t<url>" + itemList["jpg" + i].name + "</url>\n";
                xmlString += "\t\t\t<info>\n\t\t\t\t<by>" + itemList["jpg" + i].credit + "</by>\n\t\t\t</info>\n";
                xmlString += "\t\t</file>\n";
                nums.push(i);
            }
            xmlString += "\t</files>\n</data>";
            
            n = nums.length;
            var stageWidth:int = stage.stageWidth;
            var stageHeight:int = stage.stageHeight-150;
            var myBitmapData:BitmapData = new BitmapData(stageWidth, stageHeight);
            var sq:int = Math.floor(Math.sqrt(n));
            var scale:Number = Math.min(1,(stageHeight/sq)/_imgmax.selectedItem.label);
            for (i = 0; i < n; i++) {
                var j:int = nums[i];
                var tx:Number = (i % sq) * (stageWidth / sq);
                var ty:Number = Math.floor(i / sq) * (stageHeight / sq);
                var myBitmap:Bitmap = _mulitiLoader.getBitmap("jpg" + j);
                myBitmapData.draw(myBitmap, new Matrix(scale, 0, 0, scale, tx, ty));
            }
            var bitmap:Bitmap = new Bitmap(myBitmapData);
            bitmap.y = 150;
            addChild(bitmap);
            
            //info.xmlの生成
            var fileData1:ByteArray = new ByteArray();
            fileData1.writeUTFBytes(xmlString);
            _zipOut.putNextEntry(new ZipEntry("info.xml"));
            _zipOut.write(fileData1);
            _zipOut.closeEntry();
            
            _zipOut.finish();
            
            
            new PushButton(this, 360, 100, "Save", onSave);
        }
        private function onSave(e:Event):void {
            //ファイルリファレンスで保存
            var fr:FileReference = new FileReference();
            fr.save(_zipOut.byteArray, "files.zip"); // ダイアログを表示する
            function onComplete(e:Event):void {
                trace(fr.name);
            }
        }
    }
}


    /**
     * Fileローダー
     * ...
     * @author umhr
     */

    
    import flash.display.Bitmap;
    import flash.display.BitmapData;
    import flash.display.Loader;
    import flash.events.Event;
    import flash.events.IOErrorEvent;
    import flash.net.URLLoader;
    import flash.net.URLLoaderDataFormat;
    import flash.net.URLRequest;
    import flash.system.LoaderContext;
    import flash.system.Security;
    import flash.utils.Dictionary;
    import flash.utils.ByteArray;
    import flash.utils.getQualifiedClassName;
    import flash.display.MovieClip;
    class MultiLoader{
        public static var IMAGE_EXTENSIONS:Array = ["swf", "jpg", "jpeg", "gif", "png"];
        public static var TEXT_EXTENSIONS:Array = ["txt", "js", "xml", "php", "asp"];
        public static const COMPLETE:String = "complete";
        private var _listener:Function = function(event:Event):void{};
        private var _loads:Dictionary;
        private var _keyFromId:Dictionary;
        private var _loadCount:int;
        private var _itemsLoaded:int;
        public var items:Array;
        private var _binaryLoads:Dictionary = new Dictionary();
        public function MultiLoader(name:String = ""){
            _loads = new Dictionary();
            _keyFromId = new Dictionary();
            _itemsLoaded = 0;
            items = [];
        }
        public function add(url:String, props:Object = null):void {    
            var loadingItem:LoadingItem = new LoadingItem();
            loadingItem.url = url;
            loadingItem.type = getType(url, props);
            if(props){
                if(props.context){
                    loadingItem.context = props.context;
                }
                if (props.id) {
                    _keyFromId[props.id] = url;
                }
                if (props.preventCache) {
                    loadingItem.preventCache = props.preventCache;
                }
            }
            items.push(loadingItem); 
        }
        private function getType(url:String, props:Object = null):String{
            var result:String = "";
            if (props && props.type) {
                return props.type;
            }
            var i:int;
            var extension:String;
            var n:int = IMAGE_EXTENSIONS.length;
            for (i = 0; i < n; i++) {
                extension = IMAGE_EXTENSIONS[i];
                if(extension == url.substr(-extension.length).toLowerCase()){
                    result = "image";
                    break;
                }
            }
            if(result == ""){
                n = TEXT_EXTENSIONS.length;
                for (i = 0; i < n; i++) {
                    extension = TEXT_EXTENSIONS[i];
                    if(extension == url.substr(-extension.length).toLowerCase()){
                        result = "text";
                        break;
                    }
                }
            }
            return result;
        }
        
        public function start():void{
            var n:int = items.length;
            for (var i:int = 0; i < n; i++) {
                var type:String = items[i].type;
                var url:String = items[i].url;
                url += (items[i].preventCache)?"?rand=" + Math.random():"";
                var uRLRequest:URLRequest = new URLRequest(url);
                if(type == "image"){
                    _loads[items[i].url] = loadImage(uRLRequest, items[i].context);
                }else if(type == "text"){
                    _loads[items[i].url] = loadText(uRLRequest);
                }else if (type == "byteImage") {
                    byteImage(uRLRequest, items[i].context);
                }else if(type == "binary"){
                    _loads[items[i].url] = loadBinary(uRLRequest);
                }
            }
        }
        public function addEventListener(type:String,listener:Function):void{
            _listener = listener;
        }
        public function getBitmap(key:String):Bitmap{
            key = keyMatching(key);
            var bitmap:Bitmap;
            try{
                if (getQualifiedClassName(_loads[key].content) == "flash.display::MovieClip") {
                    var mc:MovieClip = _loads[key].content;
                    var bitmapData:BitmapData = new BitmapData(mc.width, mc.height);
                    bitmapData.draw(mc);
                    bitmap = new Bitmap(bitmapData);
                }else {
                    bitmap = _loads[key].content;
                }
            }catch (e:*) {
                //type == "binary"の場合
                if(_binaryLoads[key]){
                    bitmap = _binaryLoads[key].content;
                }
                //bitmap = new Bitmap();
            }
            return bitmap;
        }
        public function getBitmapData(key:String):BitmapData{
            key = keyMatching(key);
            var bitmap:Bitmap = getBitmap(key);
            var bitmapData:BitmapData = new BitmapData(bitmap.width, bitmap.height);
            bitmapData.draw(bitmap);
            return bitmapData;
        }
        private function loadImage(url:URLRequest, context:LoaderContext = null):Loader {
            var loader:Loader = new Loader();
            loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComp);
            loader.load(url, context);
            return loader;
        }
        private function byteImage(url:URLRequest, context:LoaderContext = null):void {
            var loader:Loader = new Loader();
            loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadBytes);
            loader.load(url, context);
            function loadBytes(event:Event):void {
                _loads[url.url] = new Loader();
                _loads[url.url].contentLoaderInfo.addEventListener(Event.COMPLETE, onComp);
                _loads[url.url].loadBytes(event.target.bytes);
            }
        }
        public function getBinary(key:String):ByteArray {
            var byteArray:ByteArray;
            try {
                byteArray = _loads[keyMatching(key)].contentLoaderInfo.bytes;
            }catch (e:*) {
                //type == "binary"の場合
                byteArray = _loads[keyMatching(key)].data;
            }
            
            return byteArray;
        }
        
        public function getText(key:String):String {
            key = keyMatching(key);
            return key?_loads[key].data:key;
        }
        public function getXML(key:String):XML {
            return new XML(getText(key));
        }
        private function keyMatching(key:String):String {
            return _loads[key]?key:_keyFromId[key];
        }
        private function loadText(url:URLRequest):URLLoader{
            var loader:URLLoader = new URLLoader();
            loader.addEventListener(Event.COMPLETE, onComp);
            loader.load(url);
            return loader;
        }
        private function loadBinary(url:URLRequest):URLLoader{
            var loader:URLLoader = new URLLoader();
            loader.addEventListener(Event.COMPLETE, loadBytes);
            loader.dataFormat = "binary";
            loader.load(url);
            return loader;
            function loadBytes(event:Event):void {
                _binaryLoads[url.url] = new Loader();
                _binaryLoads[url.url].contentLoaderInfo.addEventListener(Event.COMPLETE, onComp);
                _binaryLoads[url.url].loadBytes(event.target.data);
            }
        }
        private function onComp(event:Event):void {
            _itemsLoaded ++;
            if (_itemsLoaded == items.length) {
                _itemsLoaded = 0;
                _listener(event);
            }
        }
        public function get itemsTotal():int{
            return items.length;
        }
        public function get itemsLoaded():int{
            return _itemsLoaded;
        }
        public function get loadedRatio():Number {
            return _itemsLoaded / items.length;
        }
    }


import flash.net.URLRequest;
import flash.system.LoaderContext;
class LoadingItem{
    public var url:String;
    public var preventCache:Boolean;
    public var type:String;
    public var status:String;
    public var context:LoaderContext;
    public function LoadingItem(){};
}