Posts Tagged ‘as3’

Updateted : How to write Jpeg || Png Files in Swf Files

Today I wrote a new Class using swf assist for writing Jpeg or PNG files to a SWF File.

Now you could use :

 actionscript3 |  copy |? 
1
_imagePro = new ImageToSwfProcessor();
2
_imagePro.addEventListener(ImageProcessorEvent.NEXT_FILE, handleNextFile, false, 0, true);
3
_imagePro.writeSwfFromImage(image:*,quality : int ,"png" || "jpeg" : String, framecount : int);

Method wirteSwfFromImage has some Parameters.

1) The decent File as swf, jpeg or what else.

2) quality is used if image is jpeg or swf.

3) type is used to determ the current file. Only png or jpeg are used

4) framecount used to increment frames.

The Listener is called if you have many Files to store in a swf file. After each swf writing Process that listener would dispatch.

Here is that one.

 actionscript3 |  copy |? 
001
/**
002
 * Copyright 04.09.2009 Christian Sobolewski
003
 * 
004
 * usage : com.cs.imageProcessor
005
 * 
006
 * Parameters:
007
 * 
008
 * Version:
009
 * 
010
 * History:
011
 * 
012
 * com.cs.imageProcessor.ImageProcessor
013
 * @author Christian Sobolewski
014
 */
015
package com.cs.imageProcessor {
016
	import com.adobe.images.JPGEncoder;
017
	import com.adobe.images.PNGEncoder;
018
	import com.cs.logging.SOS;
019
 
020
	import org.libspark.swfassist.io.ByteArrayOutputStream;
021
	import org.libspark.swfassist.swf.io.SWFWriter;
022
	import org.libspark.swfassist.swf.io.WritingContext;
023
	import org.libspark.swfassist.swf.structures.FillStyle;
024
	import org.libspark.swfassist.swf.structures.FillStyleTypeConstants;
025
	import org.libspark.swfassist.swf.structures.SWF;
026
	import org.libspark.swfassist.swf.structures.ShapeWithStyle;
027
	import org.libspark.swfassist.swf.structures.StraightEdgeRecord;
028
	import org.libspark.swfassist.swf.structures.StyleChangeRecord;
029
	import org.libspark.swfassist.swf.tags.DefineBitsJPEG3;
030
	import org.libspark.swfassist.swf.tags.DefineShape;
031
	import org.libspark.swfassist.swf.tags.PlaceObject2;
032
	import org.libspark.swfassist.swf.tags.SetBackgroundColor;
033
	import org.libspark.swfassist.swf.tags.ShowFrame;
034
 
035
	import flash.display.BitmapData;
036
	import flash.display.Sprite;
037
	import flash.events.Event;
038
	import flash.events.EventDispatcher;
039
	import flash.events.IOErrorEvent;
040
	import flash.events.MouseEvent;
041
	import flash.events.ProgressEvent;
042
	import flash.events.SecurityErrorEvent;
043
	import flash.net.FileReference;
044
	import flash.utils.ByteArray;
045
 
046
	/**
047
	 * @author Christian Sobolewski
048
	 */
049
	public class ImageToSwfProcessor extends EventDispatcher {
050
 
051
		private var _swf : SWF;
052
		private var _bytes : ByteArray;
053
		private var _fileRef : FileReference;
054
		private var _name : String;
055
		private var _eof : Sprite;
056
 
057
		public function ImageToSwfProcessor() {
058
		}
059
 
060
		public function writeSwfFromImage(image : *, quality : int, type : String , frames : int = 1, bgColor : int = 0x000066) : BitmapData {
061
			_name = image.name.split(","+type).join("").toString();
062
 
063
			var w : Number = image.width;
064
			var h : Number = image.height;
065
 
066
			_swf = new SWF();
067
			_swf.header.version = 9;
068
			_swf.header.isCompressed = false;
069
			_swf.header.frameSize.xMax = image.width;
070
			_swf.header.frameSize.yMax = image.height;
071
			_swf.header.frameRate = 1;
072
			_swf.header.numFrames = 1;	
073
 
074
			var bg : SetBackgroundColor = new SetBackgroundColor();
075
			bg.backgroundColor.fromUint(bgColor);
076
			_swf.tags.addTag(bg);
077
 
078
			var bmd : BitmapData;
079
 
080
			if (type == "png") {
081
				bmd = new BitmapData(w, h, true, 0x000000ff);
082
				bmd.draw(image);
083
				_bytes = PNGEncoder.encode(bmd);
084
			} else {
085
				bmd = new BitmapData(w, h, false);
086
				bmd.draw(image);
087
				_bytes = new JPGEncoder(quality).encode(bmd);
088
			}		
089
 
090
//			SOS.alert("image.width = " + image.width);
091
//			SOS.alert("image.height= " + image.height);
092
 
093
			for (var i : uint = 0;i < frames;++i) {
094
 
095
				var defineJPEG : DefineBitsJPEG3 = new DefineBitsJPEG3();
096
				defineJPEG.characterId = (i * 2) + 1;
097
				defineJPEG.jpegData = _bytes;
098
 
099
				_swf.tags.addTag(defineJPEG);
100
 
101
				var defineShape : DefineShape = new DefineShape();
102
				defineShape.shapeId = (i * 2 + 1) + 1;
103
				defineShape.shapeBounds.xMax = w;
104
				defineShape.shapeBounds.yMax = h;
105
				var fillStyle : FillStyle = new FillStyle();
106
				fillStyle.fillStyleType = FillStyleTypeConstants.CLIPPED_BITMAP_FILL;
107
				fillStyle.bitmapId = (i * 2) + 1;
108
				fillStyle.bitmapMatrix.hasScale = true;
109
				fillStyle.bitmapMatrix.scaleX = 0;
110
				fillStyle.bitmapMatrix.scaleY = 0;
111
				var shape : ShapeWithStyle = defineShape.shapes;
112
				shape.fillStyles.fillStyles.push(fillStyle);
113
				var r1 : StyleChangeRecord = new StyleChangeRecord();
114
				r1.fillStyle0 = 1;
115
				r1.moveDeltaX = 0;
116
				r1.moveDeltaY = 0;
117
				r1.stateFillStyle0 = true;
118
				r1.stateMoveTo = true;
119
				var r2 : StraightEdgeRecord = new StraightEdgeRecord();
120
				r2.verticalLine = true;
121
				r2.deltaY = h;
122
				var r3 : StraightEdgeRecord = new StraightEdgeRecord();
123
				r3.horizontalLine = true;
124
				r3.deltaX = w;
125
				var r4 : StraightEdgeRecord = new StraightEdgeRecord();
126
				r4.verticalLine = true;
127
				r4.deltaY = -h;
128
				var r5 : StraightEdgeRecord = new StraightEdgeRecord();
129
				r5.horizontalLine = true;
130
				r5.deltaX = -w;
131
				shape.shapeRecords.push(r1, r2, r3, r4, r5);
132
 
133
				_swf.tags.addTag(defineShape);
134
 
135
				var placeObject : PlaceObject2 = new PlaceObject2();
136
				placeObject.characterId = (i * 2 + 1) + 1;
137
				placeObject.depth = i + 1;
138
				placeObject.hasCharacter = true;
139
 
140
				_swf.tags.addTag(placeObject);
141
				_swf.tags.addTag(new ShowFrame());
142
				_swf.header.numFrames++;
143
			}
144
 
145
 
146
			var swfBytes : ByteArray = new ByteArray();
147
 
148
			var wc : WritingContext = new WritingContext();
149
			//			wc.length = 5000;
150
 
151
			var write : SWFWriter = new SWFWriter();
152
			write.writeSWF(new ByteArrayOutputStream(swfBytes), wc, _swf);
153
 
154
			_fileRef = new FileReference();
155
			_fileRef.addEventListener(Event.COMPLETE, handleCompleteEvent, false, 0, true);
156
			_fileRef.addEventListener(ProgressEvent.PROGRESS, handleProgressEvent, false, 0, true);
157
			_fileRef.addEventListener(Event.CANCEL, handleCancelEvent, false, 0, true);
158
			_fileRef.addEventListener(SecurityErrorEvent.SECURITY_ERROR, handleSecurityEvent, false, 0, true);
159
			_fileRef.addEventListener(IOErrorEvent.IO_ERROR, onSaveError, false, 0, true);
160
			_fileRef.addEventListener(Event.OPEN, onOpen, false, 0, true);
161
 
162
			_fileRef.save(swfBytes, _name + ".swf");
163
 
164
			/**
165
			 * strange things happen here. if you dont activate Event.ENTER_FRAME no Event.COMPLETE will fire !!! 
166
			 */
167
 
168
			_eof = new Sprite();
169
			_eof.addEventListener(Event.ENTER_FRAME, handleEof, false, 0, true);
170
 
171
			return bmd;
172
		}
173
 
174
		private function handleEof(event : Event) : void {
175
			if(_fileRef.data) SOS.alert(_fileRef.data);
176
		}
177
 
178
		private function onOpen(event : Event) : void {
179
//			SOS.alert('onOpen: ' + (onOpen));
180
		}
181
 
182
		private function handleClick(event : MouseEvent) : void {
183
//			SOS.alert('handleClick: ' + (handleClick));
184
		}
185
 
186
		private function onSaveError(event : IOErrorEvent) : void {
187
//			SOS.alert('onSaveError: ' + (onSaveError));
188
		}
189
 
190
		private function handleSecurityEvent(event : SecurityErrorEvent) : void {
191
//			SOS.alert('handleSecurityEvent: ' + (handleSecurityEvent));
192
		}
193
 
194
		private function handleCancelEvent(event : Event) : void {
195
//			SOS.alert("cancel event");
196
		}
197
 
198
		private function handleProgressEvent(event : ProgressEvent) : void {
199
			SOS.alert(event.bytesLoaded + " | " + event.bytesTotal);
200
		}
201
 
202
		private function handleCompleteEvent(event : Event) : void {
203
			if (_eof.hasEventListener(Event.ENTER_FRAME)) _eof.removeEventListener(Event.ENTER_FRAME, handleEof);
204
			dispatchEvent(new ImageProcessorEvent(ImageProcessorEvent.NEXT_FILE))
205
//			SOS.alert("save complete");
206
		}
207
	}
208
}
209

http://privatefunction.net/wp-content/plugins/sociofluid/images/digg_32.png http://privatefunction.net/wp-content/plugins/sociofluid/images/delicious_32.png http://privatefunction.net/wp-content/plugins/sociofluid/images/technorati_32.png http://privatefunction.net/wp-content/plugins/sociofluid/images/google_32.png http://privatefunction.net/wp-content/plugins/sociofluid/images/facebook_32.png http://privatefunction.net/wp-content/plugins/sociofluid/images/mixx_32.png http://privatefunction.net/wp-content/plugins/sociofluid/images/twitter_32.png

Securimage PHP Captcha AS3 Class

about1

This CAPTCHA Class uses Securimage. You can get it here

Securimage is an open-source free PHP CAPTCHA script for generating complex images and CAPTCHA codes to protect forms from spam and abuse…

show.php

  |  copy |? 
1
2
include 'securimage.php';
3
$img = new securimage();
4
$img->show();
5

To load the created image, just write an URLLoader than a Loader, that loads the URLLoader data ….

Captcha.as

 as3 |  copy |? 
01
02
 public class Captcha extends Sprite
03
 {
04
 private var _loader:URLLoader;
05
 private var _captchadata:BitmapData;
06
 private var _captcha:Bitmap;
07
 private var _cont:Sprite;
08
09
 public function Captcha()
10
 {
11
 this._cont = new Sprite();
12
 this._cont.useHandCursor = true;
13
 this._cont.buttonMode = true;
14
15
 this._loader = new URLLoader();
16
 this._loader.dataFormat = URLLoaderDataFormat.BINARY;
17
 var url:String = "show.php";
18
 var urlReq:URLRequest = new URLRequest(url);
19
20
 this._loader.addEventListener(Event.COMPLETE, completeHandler);
21
 this._loader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
22
 this._loader.load(new URLRequest(url));
23
 }
24
 private function ioErrorHandler(e:IOErrorEvent):void
25
 {
26
 //SOS.alert(_e.toString());
27
 }
28
 private function completeHandler(e:Event):void 
29
 {
30
 this._loader.removeEventListener(Event.COMPLETE, completeHandler);
31
 this._loader.removeEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
32
33
 var myLoader:Loader = new Loader();
34
 myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, createCaptcha);
35
   
36
 var byteArr:ByteArray = new ByteArray();
37
 byteArr = this._loader.data;
38
39
 if(byteArr.length != 0) { myLoader.loadBytes(this._loader.data); } 
40
 else { /* SOS.alert("error"); */ }
41
 }
42
 private function createCaptcha(e:Event):void
43
 {
44
 this._captchadata = new BitmapData(175, 45, false, 0xFFFFFF); //sizes of secureimage.php ~ Line 89
45
 this._captchadata = (e.target.content).bitmapData;
46
47
 this._captcha = new Bitmap(this._captchadata, "auto", true);
48
 this._captcha.x = 920;
49
 this._captcha.y = 92;
50
 this._cont.addChild(this._captcha);
51
 this._cont.addEventListener(MouseEvent.MOUSE_DOWN , renew);
52
 this.addChildAt(this._cont,0);
53
 }
54
 private function renew(_me:MouseEvent):void
55
 {
56
 this._cont.removeChildAt(0);
57
 var url:String = "show.php?"+Math.random()*100;
58
 var urlReq:URLRequest = new URLRequest(url);
59
60
 this._loader.addEventListener(Event.COMPLETE, completeHandler);
61
 this._loader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
62
 this._loader.load(new URLRequest(url));
63
64
 }
65
 }
66

I hard-coded some dimensions inside the class, and some other ugly things, so feel free to change for your needs.
But don’t forget to put the Math.random() after the URI to refresh the captcha, this can avoid caching issues.
You can see this class Working here. Click on the share Btn.

Sure, this class can be used to load nearly all types of binary image data ….

http://privatefunction.net/wp-content/plugins/sociofluid/images/digg_32.png http://privatefunction.net/wp-content/plugins/sociofluid/images/delicious_32.png http://privatefunction.net/wp-content/plugins/sociofluid/images/technorati_32.png http://privatefunction.net/wp-content/plugins/sociofluid/images/google_32.png http://privatefunction.net/wp-content/plugins/sociofluid/images/facebook_32.png http://privatefunction.net/wp-content/plugins/sociofluid/images/mixx_32.png http://privatefunction.net/wp-content/plugins/sociofluid/images/twitter_32.png

Live audio visualization in flash pt I

bytearray

Just for a short overview,

I sometimes play drum and bass on parties. To improve the audience experience, I use flash to visualize the digital culture I’m living. For this, I wrote some applications in flash and air. These apps are more experiments to find out how my sound can influence visual media to generate a special atmosphere.

Sometimes some people notice what I am doing or know what is happening. Therefore, questions came up and it is difficult to have a productive conversation at a party….

So why flash?

I think the main reason was that I wanted to experiment with Flash and later on with the new features of the player 10.

So let us get started.

The first step to reach the stuff I had in mind was to grab the audio signal. I have a line-in, so let us take a look what possibilities I have in flash to use this. I found the flash.media package providing some classes to access the microphone and the sound spectrum. I found out that it was not really easy to get apply the computeSpectrum method on the microphone. So I thought. O.K. I’ll code a Java app that catches the audio signal, computes spectrum and send this data as bytearray to flash. However, this was not very cool, even having some java code, I could re use and I wanted to stay with flash.

I explored the possibilities and none of them were easy and latency efficient for my purposes. I really needed some time to find the solution and it was sooo simple !

Setup a streaming Server on your computer. My choice after some tests was Icecast2 here is a sample of my config:

  |  copy |? 
01
02
<icecast>
03
	<limits>
04
        	<sources>2</sources>
05
 <queue-size>0</queue-size>
06
 <burst-on-connect>1</burst-on-connect>
07
 <burst-size>0</burst-size> 
08
    </limits>
09
    <authentication>
10
        <source-password>hackme</source-password>
11
        <relay-password>hackme</relay-password>
12
        <admin-user>admin</admin-user>
13
        <admin-password>hackme</admin-password>
14
    </authentication>
15
 
16
    <hostname>localhost</hostname>
17
	<listen-socket>
18
<port>6666</port>
19
    </listen-socket>
20
    <fileserve>1</fileserve>
21
<paths>
22
        <logdir>./logs</logdir>
23
        <webroot>./web</webroot>
24
        <adminroot>./admin</adminroot>
25
        <alias source="/" dest="/status.xsl">
26
    </alias>
27
    <logging>
28
        <accesslog>access.log</accesslog>
29
        <errorlog>error.log</errorlog>
30
      	<loglevel>3</loglevel> <!-- 4 Debug, 3 Info, 2 Warn, 1 Error -->
31
</logging></paths></icecast>

Setup a streaming client on your computer like Edcast and choose the right audio in.

When you get this programs running you will have a streaming server running under the following URL:

http://localhost:6666/stream

or if you are using shoutcast :

….. /;stream.nsv

So now, you can catch this audio stream from your flash app like this:

  |  copy |? 
1
2
this._sfx = new Sound();
3
var req:URLRequest = new URLRequest("http://localhost:6666/stream");// /;stream.nsv
4
var context:SoundLoaderContext = new SoundLoaderContext(0, false);
5
this._sfx.load(req, context);
6
this._channel = this._sfx.play();
7
SoundMixer.bufferTime=0;  // works for me locally
8

Now you can get the spectrum over an onEnterFrame Event with SoundMixer.computeSpectrum. I am going to explain this in part II

http://privatefunction.net/wp-content/plugins/sociofluid/images/digg_32.png http://privatefunction.net/wp-content/plugins/sociofluid/images/delicious_32.png http://privatefunction.net/wp-content/plugins/sociofluid/images/technorati_32.png http://privatefunction.net/wp-content/plugins/sociofluid/images/google_32.png http://privatefunction.net/wp-content/plugins/sociofluid/images/facebook_32.png http://privatefunction.net/wp-content/plugins/sociofluid/images/mixx_32.png http://privatefunction.net/wp-content/plugins/sociofluid/images/twitter_32.png
Return top

INFORMATION