Create a png with php and as3

For a project I was on awhile ago, I needed to decorate a character with different items of clothing. When the user was done ‘dressing’ their character, they would press a button and the whole character would shrink down so it would fit as an ornament on a tree. In order to not confuse the issue, I am going to only show the code that enables you to take a movieclip and create a png from it. In order to do this, you will need to include the Flex SDK as a part of your flash build (for the Base64Encoder class) and you need to download as3corelib. To include the Flex SDK, in your Flash preferences add this line: (Mac OSX)

//VERSION will prob be 3.5, 4 etc...
/Applications/Adobe Flash Builder 4/sdks/flex_sdk_VERSION/frameworks/projects/framework/src

Code after the jump…

[download id=”12″]

You will need to place the flash file and php file next to eachother on the webserver. (I named my the php file CreatePNG). When you run the Flash file and press the create button, you will notice that a png file is created on your web server next to your source files.

PHP Code:

CreatePNG.php

Actionscript Code:

package {
	
	import flash.display.*;
	import flash.events.*;
	import flash.net.*;
	import flash.utils.*;
	
	import flash.system.LoaderContext;
	import flash.net.URLRequest;
	
	import flash.geom.Matrix;	
	import flash.geom.Rectangle;
	
	import com.adobe.images.PNGEncoder;
	import mx.utils.Base64Encoder;

	public class CreatePngTestStar extends MovieClip{

		public function CreatePngTestStar():void {
			addEventListener(Event.ADDED_TO_STAGE, init, false, 0, true);
		}
		
		private function init(e:Event):void {
			create_btn.addEventListener(MouseEvent.MOUSE_DOWN, shrinkMe, false, 0, true);
		}
		
		private function shrinkMe(me:MouseEvent):void {
			createPng();
		}

		private function createPng():void {
			var unid_date:Date = new Date();
			var unid:Number = unid_date.getTime();
			var rect:Rectangle = new Rectangle (0,0,star.width,star.height);
			
			var m:Matrix = new Matrix();
			m.scale(.25, .25);
			
			var bmpData:BitmapData=new BitmapData(star.width, star.height, true, 0xFFFFFF);
			bmpData.draw(star, m);
			
			var ba:ByteArray = PNGEncoder.encode(bmpData);
			
			var base64:Base64Encoder = new Base64Encoder();
			base64.encodeBytes(ba);
			
			var loader:URLLoader = new URLLoader();
			var request:URLRequest=new URLRequest("http://localhost:8888/wwwtests/createPNGTest/CreatePNG.php");
			request.method=URLRequestMethod.POST;
			var data:URLVariables = new URLVariables();
			
			data.fileData=base64;
			data.fileName="star_"+unid.toString();
			
			request.data=data;
			loader.addEventListener(Event.COMPLETE, onCreated);
			loader.load(request);
		}

		private function onCreated(e:Object):void {
			trace("onCreated: " + e);
		}
	}
}

Comments

Leave a Reply