スキップしてメイン コンテンツに移動

投稿

ラベル(ActionScript)が付いた投稿を表示しています

ActionScript 3.0: Capture Web Page Image

In my recent post, I was trying to find out easy way to capture we page image. Today, I will show you my small code tip for capturing web page and saving it as image by ActionScript 3.0. WebPageCapture class This is the main class for capturing web page and save it as image. A few points I should comment... In captureAndSave method, I have used timer because even after Complete event is triggered, somehow sometimes web page is not rendered properly... (might be depends on web site or lazy javascript loading.) requstQueue field is for making sure the request is processed one by one after the former image capturing request is done. You can avoid this if you create HTMLLoader instance for each request. Looks default JPEGEncoder is quite slow.... I have googled and found the following great article. If you are interested in performance, see this excellent post . I was amazed actually :D If you are interested in asynchronous encoding, see this marvelous post . I was impressed :D

ActionScript 3.0: Download Resource and Save as File Asynchronously

Here is a utility class for downloading resource and saving as file asynchronously . package utils.file { import flash.events.Event; import flash.events.EventDispatcher; import flash.events.ProgressEvent; import flash.filesystem.File; import flash.filesystem.FileStream; import flash.filesystem.FileMode; import flash.net.URLLoader; import flash.net.URLLoaderDataFormat; import flash.net.URLRequest; public class AsyncFileSaveDownloader extends EventDispatcher { public function AsyncFileSaveDownloader() { } public function download(url:String, path:String):void { var loader:URLLoader = new URLLoader(); loader.dataFormat = URLLoaderDataFormat.BINARY; loader.addEventListener(Event.COMPLETE, completeDownload); loader.load(new URLRequest(url)); function completeDownload(cevt:Event):void { l

Ant Build Script for ActionScript 3.0 (AIR Application)

This is my ant build script used for building app. You know FlashDevelop can build swf however it only compiles minimum classes directly used in the program. So I always run ant build script in order to compile all ".as" and ".mxml" source files If you would like to use my ant script, need some preparation.... Flex PMD: You can download Flex PMD, which is used in my ant script, from here . PMD xslt: I just downloaded official sourceforge PMD zip (the version is 5.0.0 when I wrote this article) and simply picked up some useful xslt from pmd-src-5.0.0/etc/xslt My project directory hierarchy is something like this... <?xml version="1.0" encoding="utf-8" ?> <project name="DukeSoftwareBuildAS3" default="all" basedir="."> <property name="root.dir" value=".." /> <property file="${root.dir}/proj.properties" /> <property file="build.prop

ActionScript 3.0: Resize Image

Main flow part code. package utils.tool { import flash.display.Bitmap; import flash.display.BitmapData; import flash.display.Loader; import flash.net.URLRequest; import flash.events.Event; import utils.ImageUtils; public class ImageResizer { private var maxW:int, maxH:int; private var smoothing:Boolean; private var saveFunction:Function; public function ImageResizer(maxW:int, maxH:int, smoothing:Boolean = false, type:String="jpg") { this.maxW = maxW; this.maxH = maxH; this.smoothing = smoothing; if (type === "png") { saveFunction = ImageUtils.saveBitmapDataAsPNGAsync; } else if(type === "jpg"){ saveFunction = ImageUtils.saveBitmapDataAsJPEGAsync; } else { throw new Error("Not Supported"); } }

ActionScript 3.0: Save BitmapData As JPEG or PNG

public static function saveBitmapDataAsJPEG(path:String, bitmapData:BitmapData, quality:Number=50.0):void { saveByteData(new JPEGEncoder(quality).encode(bitmapData), path); } public static function saveBitmapDataAsJPEGAsync(path:String, bitmapData:BitmapData, quality:Number=50.0):void { saveByteDataAsync(new JPEGEncoder(quality).encode(bitmapData), path); } public static function saveBitmapDataAsPNG(path:String, bitmapData:BitmapData):void { saveByteData(new PNGEncoder().encode(bitmapData), path); } public static function saveBitmapDataAsPNGAsync(path:String, bitmapData:BitmapData):void { saveByteDataAsync(new PNGEncoder().encode(bitmapData), path); } Here is my IO Utility methods. public static function saveByteData(data:ByteArray, path:String):void { try { var file:File = new File(path); var fs:FileStream = new FileStream(); fs.open(file, FileMode.WRITE); fs.writeBytes(data); fs.close(); } catch (err:IOError) { trace(err); } } public static function saveB

ActionScript 3.0: Loading Bytes from URL

I wrote a utility class for loading bytes from URL because the official method needs a lot of preparation. Here is the usage. var loader:ByteLoadHelper = new ByteLoadHelper(); loader.addEventListener(ByteLoadEvent.COMPLETE, completeHandler); loader.load(url); function completeHandler(evt:ByteLoadEvent):void { loader.removeEventListener(ByteLoadEvent.COMPLETE, completeHandler); var bytes:ByteArray = evt.data; // do something nice :D } Here is the core code. package utils.tool { import flash.events.Event; import flash.events.EventDispatcher; import flash.net.URLLoader; import flash.net.URLLoaderDataFormat; import flash.net.URLRequest; import flash.utils.ByteArray; public class ByteLoadHelper extends EventDispatcher { public function ByteLoadHelper() { } public function load(url:String):void { var urlLoader:URLLoader = new URLLoader(); urlLoader.dataFormat = URLLoa

ActionScript 3.0: Dictionary Utility Methods (Delete All Entries, Count All Entries, etc.))

public class DictionaryUtils { public function DictionaryUtils() { } public static function forEachBySortedValue(dict:Dictionary, compare:Function, callback:Function):void { var v:Vector.<Object> = extractValues(dict); v.sort(compare); for each(var value:Object in v) { callback(value); } } public static function forEachBySortedKey(dict:Dictionary, compare:Function, callback:Function):void { var v:Vector.<Object> = extractKeys(dict); v.sort(compare); for each(var key:Object in v) { callback(key, dict[key]); } } public static function extractValues(dict:Dictionary):Vector.<Object> { var v:Vector.<Object> = new Vector.<Object>(); for each(var value:Object in dict) { v.push(value); } return v; } public static function extractKeys(dict:Dictionary):Vector.<Object> { var v:Vector.<Object> = new Vector.<Object>(); for (var key:Object in dict) { v.push(key); } return v; } pu

ActionScript 3.0: Digging Directory Recursively And Process Each File

This class aims to parse directory and do something for each file. You should just override proper methods, then call process method like this. new DirectoryDigger().process("c:/temp"); package utils.file { import flash.filesystem.File; public class DirectoryDigger { public function DirectoryDigger() { } public function process(path:String):Object { var file:File = new File(path); preProcess(file); processBody(file); return postProcess(file); } protected function processBody(file:File):void { if (file.isDirectory) { preProcessDir(file); var files : Array = file.getDirectoryListing(); for (var i : int = 0; i < files.length; i++) { processBody(files[i] as File); } postProcessDir(file);

ActionScript 3.0: Load SWF, JPG, PNG

Hey guys! I wrote small utility method for loading swf, jpg, png etc. in ActionScript 3.0. public static function loadFromURL(url:String):Loader { var img:Loader = new Loader(); img.load(new URLRequest(url)); return img; } public static function loadFromFile(path:String):Loader { var img:Loader = new Loader(); img.loadBytes(IOUtils.readByteData(path)); return img; } public static function load(url:String, format:String):URLLoader { var loader:URLLoader = new URLLoader(); loader.dataFormat = format; loader.addEventListener(Event.COMPLETE, completeHandler); loader.load(new URLRequest(url)); function completeHandler(event:Event):void { loader.removeEventListener(Event.COMPLETE, completeHandler); //trace(event.target.data); } return loader; }

ActionScript 3.0: Hit Youtube API

I wrote a tiny program for getting Youtube video information by hitting Youtube API in ActionScript 3.0. Some generic classes or methods might be missing but I think you can easily guess what they are doing and can add them easily yourself. Example Usage Ok, starting from the example usage. package utils.video { import flash.display.Sprite; import utils.file.SyncFileSaveDownLoader; import utils.ITaskProgressCounter; import utils.TaskProgressCounter; import utils.video.youtube.YoutubeAPI; import utils.video.YoutubeFLVURLGetEvent; import utils.video.youtube.YoutubeLocalCacheManager; import utils.video.youtube.YoutubeVideoEntryDispatcher; import utils.video.youtube.YoutubeVideoEntryEvent; public class Tester extends Sprite { private var downloader:SyncFileSaveDownLoader = new SyncFileSaveDownLoader(); private var youtubeLocalCacheManager:YoutubeLocalCacheManager = new YoutubeLocalCacheManager("c:\\temp\\youtube&qu

ActionScript 3.0: Read catalog.xml

I have written reading catalog.xml program in ActionScript 3.0. I know my code is not perfect however I make my code public because I would like to help someone who would like to analyze catalog.xml... hope it helps :) In short the code is simply reading xml file. package utils.tool { public class CatalogXmlReader { // you should change the namespace based on flash version private static const NS:String = "http://www.adobe.com/flash/swccatalog/9"; public function CatalogXmlReader() { } public function create(xml:XML):SWCCatalog { var ns:Namespace = getDefaultNamespace(xml); if (!(ns.uri === NS)) throw new Error("Namespace is wrong"); var versions:XMLList = xml.child(new QName(ns, "versions")); var swcVersion:SWCVersions = new SWCVersions(); swcVersion.swcVersion = versions

Simplest AIR Application Launch Command

I always forgot how to launch AIR application from command line for debugging purpose :( As you know there are lot of command line options for adl but I think the simplest command is something like below: {PATH_TO_FLEX_SDK}\bin\adl.exe application.xml bin FlashDevelop's prepared bat files, which are generated when you created AIR project, also help your understanding for how the AIR app is launched.

ActionScript 3.0: Test Tools

Test Suite AsUnit : FlashDevelop からでも使えます。 AS3Unit :ActionScript 3のためのテストフレームワークです。JUnitのActionScript 3.0版といったところでしょうか。 Spark Project 上で公開されています。 FlexUnit : AdobeLabs で公開されているTestSuitです。 FlexMonkey : FlexのためのUIのテストフレームワークです。 FlexPMD : Javaで有名なPMDのFlex版といったところでしょうか。 Code Coverage Tool flexcover :Code Coverage Tool for Flex and AIR applications.

ActionScript3.0: Reflection Example

I introduce some tips for reflection (not reflection of image but "programatic") of ActionScript 3.0. getDefinitionByName If you would like to Class object getDefinitionByName function should help. var c:Class = getDefinitionByName("flash.display.Sprite") as Class; If you would like to know details information of Class you can use describeType , which returns class information as Xml format. Reflective Class Instantiation import flash.utils.getDefinitionByName; public class Instantiator { private var classRef:Class; public function Instantiator(className:String) { this.classRef = getDefinitionByName(className) as Class; } public function newInstance(...args):Object { if(args.length == 0){ return new classRef(); } else { return new classRef(args); } } } Example usage: import flash.display.Sprite; import seedion.io.XMLExporter; // class will be instantiated at line with (*) import utils.tool.Instantiat

ActionScript 3.0: Play Sound with Drawing FFT Spectrum

I have written simple example for playing mp3 sound with drawing sound FFT spectrum. Here is the code. package utils.sound { import flash.display.Sprite; import flash.events.Event; import flash.events.MouseEvent; import flash.utils.ByteArray; import flash.media.SoundMixer; import flash.media.Sound; import ui.Button; import flash.net.URLRequest; import flash.media.SoundChannel; public class SoundPlayerTemp extends Sprite { private static const MAX_CHANEL :int = 256; private var w:int = 1; private var maxSize:int = 400; private const OFFSET_Y:int = 20; private var urlReq :URLRequest = new URLRequest("file://c:/temp/test.mp3"); // any button is fine.... private var startButton:Button = new Button(maxSize - 50, 100, OFFSET_Y); private var snd:Sound = new Sound(); private var sndCh:SoundChannel; private var playState:B

ActionScript 3.0: String Utility Methods (trim, startsWith, endsWith etc.)

public class StringUtils { public function StringUtils() { } public static function concatAsString(array:Array):String { var ret:String = ""; for each(var str:String in array) { ret += str; } return ret; } public static function concatAllAsString(delimita:String, ...strs):String { if (strs == null || strs.length == 0) { return ""; } var ret:String = ""; for each(var str:String in strs) { ret += delimita + str } return ret.substr(1, ret.length - 1); } public static function trim(src:String):String { return src.replace(/^[\s\t]+(.+)[\s\t]+$/, "$1"); } public static function endsWith(str:String, seacrh:String):Boolean { return str.length > seacrh.length && str.substr(seacrh.length-1, seacrh.length) === seacrh; } public static function startsWith(prefix:String, testStr:String):Boolean { return testStr.length >= prefix.length && testStr.substr(0, prefix.len

ActionScript 3.0 Garbage Collectionのテスト

Duke Software: ActionScript 3.0 でのSoundのメモリリーク解消方法 の投稿にブックマークをして下さっている方がいるのに、自分で何もテストしないのはお恥ずかしいので、Flashのメモリ管理、特にガーベッジコレクションについてその挙動を調べてみました! 結論から書きますと、 Array を使うのが最も安全なようです。(あくまで私がテストした環境においてです。保証はできません。)System.gc();を明示的に呼び出せば、下記でテストしたすべての場合でメモリが開放されますが、System.gc();はデバッグ版のFlash Playerでしか呼びさせなかったはずなので、止めておいた方が無難だと思います。 テスト環境 Flex :Flex 3.5 (build 12683) Flash Player:WIN 10,0,42,34 (Capabilities.versionから取得) 方法: 1) クラスにフィールド(1. Array, 2. Object, 3. 自作のdynamicクラス)を定義 2) 画面をクリックするごとに、Vector. オブジェクトを生成して1)で定義したフィールドに代入 3) クリック直後とクリックイベント検知1秒後のメモリ使用量をSystem.totalMemoryで取得 1. Array - すぐに開放される package test { /** * The most safe way... * * @author Duke */ public class GarbageCollectorArrayPropertyTest extends GarbageCollectorTestBase { private var a:Array = new Array(1); public function GarbageCollectorArrayPropertyTest() { } protected override function createObject():void { // Yeah garbage collection is triggerd and works properly :) a[0] = new