5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

javascriptとas3で連携してswfのキャプチャ画像を取得する方法

5
Posted at

swfを好きなタイミングでキャプチャを撮ってローカルに保存するってことがあったのでメモ

sample.mxml
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark"
			   xmlns:mx="library://ns.adobe.com/flex/mx" width="400" height="300"
			   creationComplete="creationCompleteHandler(event)">
	<fx:Script>
		<![CDATA[
			import mx.events.FlexEvent;
			import mx.graphics.codec.PNGEncoder;
			import mx.utils.Base64Encoder;

			/**
			 * 初期化完了イベント
			 * @param event
			 */
			protected function creationCompleteHandler( event:FlexEvent ):void {
				// JSから呼ぶときの名前を登録
				ExternalInterface.addCallback( "getCapture", capture );
			}

			/**
			 * 画面のキャプチャを生成する
			 * @return base64エンコードした画像データ
			 */
			private function capture():String {
				// DisplayObjectをBitmapDataに描画
				var bmpd:BitmapData = new BitmapData( this.width, this.height );
				bmpd.draw( this );

				// Base64でエンコード
				var base64:Base64Encoder = new Base64Encoder();
				base64.encodeBytes( new PNGEncoder().encode( bmpd ) );

				return base64.toString();
			}
		]]>
	</fx:Script>
	<s:BorderContainer width="100" height="100" backgroundColor="0x00FF00" backgroundAlpha="0.5" verticalCenter="0" left="0"/>
	<s:BorderContainer width="100" height="100" backgroundColor="0xFF0000" backgroundAlpha="0.5" verticalCenter="0" right="0"/>
	<s:BorderContainer width="100" height="100" backgroundColor="0x0000FF" backgroundAlpha="0.5" verticalCenter="0" horizontalCenter="0"/>
</s:Application>

}

ExternalInterface.addCallbackでJSからメソッドをコールできるようにするのがポイント。
jsから getCapture というメソッド名で呼び出すことができるようになる。

function capture(){
	var swf = document.sample;
	// ExternalInterface.addCallbackで登録したメソッドを呼び出す
	var str = swf.getCapture();

	var png = document.createElement('img');
	png.src = "data:image/png;base64," + str;
	png.width = 400;
	png.height = 300;

	document.appendChild(png);
}
5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?