Category Archives: ActionScript 3

Adobe ActionScript 3 Programing Language

Mime Type Map Class ActionScript 3

Written by . Filed under ActionScript 3. Tagged , , , , , , , . .

Maps mime types and file extensions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
/*
  Copyright (c) 2008, Adobe Systems Incorporated
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are
  met:

  * Redistributions of source code must retain the above copyright notice,
    this list of conditions and the following disclaimer.
 
  * Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.
 
  * Neither the name of Adobe Systems Incorporated nor the names of its
    contributors may be used to endorse or promote products derived from
    this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

package com.adobe.net
{
    public class MimeTypeMap
    {
        private var types:Array =
            [["application/andrew-inset","ez"],
            ["application/atom+xml","atom"],
            ["application/mac-binhex40","hqx"],
            ["application/mac-compactpro","cpt"],
            ["application/mathml+xml","mathml"],
            ["application/msword","doc"],
            ["application/octet-stream","bin","dms","lha","lzh","exe","class","so","dll","dmg"],
            ["application/oda","oda"],
            ["application/ogg","ogg"],
            ["application/pdf","pdf"],
            ["application/postscript","ai","eps","ps"],
            ["application/rdf+xml","rdf"],
            ["application/smil","smi","smil"],
            ["application/srgs","gram"],
            ["application/srgs+xml","grxml"],
            ["application/vnd.adobe.apollo-application-installer-package+zip","air"],
            ["application/vnd.mif","mif"],
            ["application/vnd.mozilla.xul+xml","xul"],
            ["application/vnd.ms-excel","xls"],
            ["application/vnd.ms-powerpoint","ppt"],
            ["application/vnd.rn-realmedia","rm"],
            ["application/vnd.wap.wbxml","wbxml"],
            ["application/vnd.wap.wmlc","wmlc"],
            ["application/vnd.wap.wmlscriptc","wmlsc"],
            ["application/voicexml+xml","vxml"],
            ["application/x-bcpio","bcpio"],
            ["application/x-cdlink","vcd"],
            ["application/x-chess-pgn","pgn"],
            ["application/x-cpio","cpio"],
            ["application/x-csh","csh"],
            ["application/x-director","dcr","dir","dxr"],
            ["application/x-dvi","dvi"],
            ["application/x-futuresplash","spl"],
            ["application/x-gtar","gtar"],
            ["application/x-hdf","hdf"],
            ["application/x-javascript","js"],
            ["application/x-koan","skp","skd","skt","skm"],
            ["application/x-latex","latex"],
            ["application/x-netcdf","nc","cdf"],
            ["application/x-sh","sh"],
            ["application/x-shar","shar"],
            ["application/x-shockwave-flash","swf"],
            ["application/x-stuffit","sit"],
            ["application/x-sv4cpio","sv4cpio"],
            ["application/x-sv4crc","sv4crc"],
            ["application/x-tar","tar"],
            ["application/x-tcl","tcl"],
            ["application/x-tex","tex"],
            ["application/x-texinfo","texinfo","texi"],
            ["application/x-troff","t","tr","roff"],
            ["application/x-troff-man","man"],
            ["application/x-troff-me","me"],
            ["application/x-troff-ms","ms"],
            ["application/x-ustar","ustar"],
            ["application/x-wais-source","src"],
            ["application/xhtml+xml","xhtml","xht"],
            ["application/xml","xml","xsl"],
            ["application/xml-dtd","dtd"],
            ["application/xslt+xml","xslt"],
            ["application/zip","zip"],
            ["audio/basic","au","snd"],
            ["audio/midi","mid","midi","kar"],
            ["audio/mp4","f4a"],
            ["audio/mp4","f4b"],
            ["audio/mpeg","mp3","mpga","mp2"],
            ["audio/x-aiff","aif","aiff","aifc"],
            ["audio/x-mpegurl","m3u"],
            ["audio/x-pn-realaudio","ram","ra"],
            ["audio/x-wav","wav"],
            ["chemical/x-pdb","pdb"],
            ["chemical/x-xyz","xyz"],
            ["image/bmp","bmp"],
            ["image/cgm","cgm"],
            ["image/gif","gif"],
            ["image/ief","ief"],
            ["image/jpeg","jpg","jpeg","jpe"],
            ["image/png","png"],
            ["image/svg+xml","svg"],
            ["image/tiff","tiff","tif"],
            ["image/vnd.djvu","djvu","djv"],
            ["image/vnd.wap.wbmp","wbmp"],
            ["image/x-cmu-raster","ras"],
            ["image/x-icon","ico"],
            ["image/x-portable-anymap","pnm"],
            ["image/x-portable-bitmap","pbm"],
            ["image/x-portable-graymap","pgm"],
            ["image/x-portable-pixmap","ppm"],
            ["image/x-rgb","rgb"],
            ["image/x-xbitmap","xbm"],
            ["image/x-xpixmap","xpm"],
            ["image/x-xwindowdump","xwd"],
            ["model/iges","igs","iges"],
            ["model/mesh","msh","mesh","silo"],
            ["model/vrml","wrl","vrml"],
            ["text/calendar","ics","ifb"],
            ["text/css","css"],
            ["text/html","html","htm"],
            ["text/plain","txt","asc"],
            ["text/richtext","rtx"],
            ["text/rtf","rtf"],
            ["text/sgml","sgml","sgm"],
            ["text/tab-separated-values","tsv"],
            ["text/vnd.wap.wml","wml"],
            ["text/vnd.wap.wmlscript","wmls"],
            ["text/x-setext","etx"],
            ["video/mp4","f4v"],
            ["video/mp4","f4p"],           
            ["video/mpeg","mpg","mpeg","mpe"],
            ["video/quicktime","mov","qt"],
            ["video/vnd.mpegurl","m4u","mxu"],
            ["video/x-flv","flv"],
            ["video/x-msvideo","avi"],
            ["video/x-sgi-movie","movie"],
            ["x-conference/x-cooltalk","ice"]];

        /**
         * Returns the mimetype for the given extension.
         */

        public function getMimeType(extension:String):String
        {
            extension = extension.toLocaleLowerCase();
            for each (var a:Array in types)
            {
                for each (var b:String in a)
                {
                    if (b == extension)
                    {
                        return a[0];
                    }
                }
            }
            return null;
        }

        /**
         * Returns the prefered extension for the given mimetype.
         */

        public function getExtension(mimetype:String):String
        {
            mimetype = mimetype.toLocaleLowerCase();
            for each (var a:Array in types)
            {
                if (a[0] == mimetype)
                {
                    return a[1];
                }
            }
            return null;
        }

        /**
         * Adds a mimetype to the map. The order of the extensions matters. The most preferred should come first.
         */

        public function addMimeType(mimetype:String, extensions:Array):void
        {
            var newType:Array = [mimetype];
            for each (var a:String in extensions)
            {
                newType.push(a);
            }
            types.push(newType);
        }
    }
}

Have a nice day ;)
Garry Lachman

Array Until class ActionScript 3

Written by . Filed under ActionScript 3. Tagged , , , , , , , , , . .

Array Until class ActionScript 3

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
/*
  Copyright (c) 2008, Adobe Systems Incorporated
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are
  met:

  * Redistributions of source code must retain the above copyright notice,
    this list of conditions and the following disclaimer.
 
  * Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.
 
  * Neither the name of Adobe Systems Incorporated nor the names of its
    contributors may be used to endorse or promote products derived from
    this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/


package com.adobe.utils
{

    /**
    *   Class that contains static utility methods for manipulating and working
    *   with Arrays.
    *
    *   Note that all APIs assume that they are working with well formed arrays.
    *   i.e. they will only manipulate indexed values.  
    *
    *   @langversion ActionScript 3.0
    *   @playerversion Flash 9.0
    *   @tiptext
    */
     
    public class ArrayUtil
    {

        /**
        *   Determines whether the specified array contains the specified value.   
        *
        *   @param arr The array that will be checked for the specified value.
        *
        *   @param value The object which will be searched for within the array
        *
        *   @return True if the array contains the value, False if it does not.
        *
        *   @langversion ActionScript 3.0
        *   @playerversion Flash 9.0
        *   @tiptext
        */
         
        public static function arrayContainsValue(arr:Array, value:Object):Boolean
        {
            return (arr.indexOf(value) != -1);
        }  

        /**
        *   Remove all instances of the specified value from the array,
        *
        *   @param arr The array from which the value will be removed
        *
        *   @param value The object that will be removed from the array.
        *
        *   @langversion ActionScript 3.0
        *   @playerversion Flash 9.0
        *   @tiptext
        */
     
        public static function removeValueFromArray(arr:Array, value:Object):void
        {
            var len:uint = arr.length;

            for(var i:Number = len; i > -1; i--)
            {
                if(arr[i] === value)
                {
                    arr.splice(i, 1);
                }
            }                  
        }

        /**
        *   Create a new array that only contains unique instances of objects
        *   in the specified array.
        *
        *   Basically, this can be used to remove duplication object instances
        *   from an array
        *
        *   @param arr The array which contains the values that will be used to
        *   create the new array that contains no duplicate values.
        *
        *   @return A new array which only contains unique items from the specified
        *   array.
        *
        *   @langversion ActionScript 3.0
        *   @playerversion Flash 9.0
        *   @tiptext
        */
 
        public static function createUniqueCopy(a:Array):Array
        {
            var newArray:Array = new Array();

            var len:Number = a.length;
            var item:Object;

            for (var i:uint = 0; i < len; ++i)
            {
                item = a[i];

                if(ArrayUtil.arrayContainsValue(newArray, item))
                {
                    continue;
                }

                newArray.push(item);
            }

            return newArray;
        }

        /**
        *   Creates a copy of the specified array.
        *
        *   Note that the array returned is a new array but the items within the
        *   array are not copies of the items in the original array (but rather
        *   references to the same items)
        *
        *   @param arr The array that will be copies
        *
        *   @return A new array which contains the same items as the array passed
        *   in.
        *
        *   @langversion ActionScript 3.0
        *   @playerversion Flash 9.0
        *   @tiptext
        */
         
        public static function copyArray(arr:Array):Array
        {  
            return arr.slice();
        }

        /**
        *   Compares two arrays and returns a boolean indicating whether the arrays
        *   contain the same values at the same indexes.
        *
        *   @param arr1 The first array that will be compared to the second.
        *
        *   @param arr2 The second array that will be compared to the first.
        *
        *   @return True if the arrays contains the same values at the same indexes.
            False if they do not.
        *
        *   @langversion ActionScript 3.0
        *   @playerversion Flash 9.0
        *   @tiptext
        */
     
        public static function arraysAreEqual(arr1:Array, arr2:Array):Boolean
        {
            if(arr1.length != arr2.length)
            {
                return false;
            }

            var len:Number = arr1.length;

            for(var i:Number = 0; i < len; i++)
            {
                if(arr1[i] !== arr2[i])
                {
                    return false;
                }
            }

            return true;
        }
    }
}

Have Fun ;)
Garry

MD5 crypto class ActionScript 3

Written by . Filed under ActionScript 3. Tagged , , , , , , , , , , , , . .

One more useful util from as3corelib.
MD5 class crypto.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
<?
/*
  Copyright (c) 2008, Adobe Systems Incorporated
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are
  met:

  * Redistributions of source code must retain the above copyright notice,
    this list of conditions and the following disclaimer.
 
  * Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.
 
  * Neither the name of Adobe Systems Incorporated nor the names of its
    contributors may be used to endorse or promote products derived from
    this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/


package com.adobe.crypto {
   
    import com.adobe.utils.IntUtil;
    import flash.utils.ByteArray;  
    /**
     * The MD5 Message-Digest Algorithm
     *
     * Implementation based on algorithm description at
     * http://www.faqs.org/rfcs/rfc1321.html
     */

    public class MD5 {
       
        public static var digest:ByteArray;
        /**
         * Performs the MD5 hash algorithm on a string.
         *
         * @param s The string to hash
         * @return A string containing the hash value of s
         * @langversion ActionScript 3.0
         * @playerversion Flash 8.5
         * @tiptext
         */

         
        public static function hash(s:String) :String{
            //Convert to byteArray and send through hashBinary function
            // so as to only have complex code in one location
            var ba:ByteArray = new ByteArray();
            ba.writeUTFBytes(s);   
            return hashBinary(ba);
        }
       
        public static function hashBytes(s:ByteArray) :String{ 
            return hashBinary(s);
        }
       
        /**
         * Performs the MD5 hash algorithm on a ByteArray.
         *
         * @param s The string to hash
         * @return A string containing the hash value of s
         * @langversion ActionScript 3.0
         * @playerversion Flash 8.5
         * @tiptext
         */
 
        public static function hashBinary( s:ByteArray ):String {
            // initialize the md buffers
            var a:int = 1732584193;
            var b:int = -271733879;
            var c:int = -1732584194;
            var d:int = 271733878;
           
            // variables to store previous values
            var aa:int;
            var bb:int;
            var cc:int;
            var dd:int;
           
            // create the blocks from the string and
            // save the length as a local var to reduce
            // lookup in the loop below
            var x:Array = createBlocks( s );
            var len:int = x.length;
           
            // loop over all of the blocks
            for ( var i:int = 0; i < len; i += 16) {
                // save previous values
                aa = a;
                bb = b;
                cc = c;
                dd = d;            
               
                // Round 1
                a = ff( a, b, c, d, x[int(i+ 0)],  7, -680876936 );     // 1
                d = ff( d, a, b, c, x[int(i+ 1)], 12, -389564586 ); // 2
                c = ff( c, d, a, b, x[int(i+ 2)], 17, 606105819 );  // 3
                b = ff( b, c, d, a, x[int(i+ 3)], 22, -1044525330 );    // 4
                a = ff( a, b, c, d, x[int(i+ 4)],  7, -176418897 );     // 5
                d = ff( d, a, b, c, x[int(i+ 5)], 12, 1200080426 );     // 6
                c = ff( c, d, a, b, x[int(i+ 6)], 17, -1473231341 );    // 7
                b = ff( b, c, d, a, x[int(i+ 7)], 22, -45705983 );  // 8
                a = ff( a, b, c, d, x[int(i+ 8)],  7, 1770035416 );     // 9
                d = ff( d, a, b, c, x[int(i+ 9)], 12, -1958414417 );    // 10
                c = ff( c, d, a, b, x[int(i+10)], 17, -42063 );         // 11
                b = ff( b, c, d, a, x[int(i+11)], 22, -1990404162 );    // 12
                a = ff( a, b, c, d, x[int(i+12)],  7, 1804603682 );     // 13
                d = ff( d, a, b, c, x[int(i+13)], 12, -40341101 );  // 14
                c = ff( c, d, a, b, x[int(i+14)], 17, -1502002290 );    // 15
                b = ff( b, c, d, a, x[int(i+15)], 22, 1236535329 );     // 16
               
                // Round 2
                a = gg( a, b, c, d, x[int(i+ 1)],  5, -165796510 );     // 17
                d = gg( d, a, b, c, x[int(i+ 6)],  9, -1069501632 );    // 18
                c = gg( c, d, a, b, x[int(i+11)], 14, 643717713 );  // 19
                b = gg( b, c, d, a, x[int(i+ 0)], 20, -373897302 );     // 20
                a = gg( a, b, c, d, x[int(i+ 5)],  5, -701558691 );     // 21
                d = gg( d, a, b, c, x[int(i+10)],  9, 38016083 );   // 22
                c = gg( c, d, a, b, x[int(i+15)], 14, -660478335 );     // 23
                b = gg( b, c, d, a, x[int(i+ 4)], 20, -405537848 );     // 24
                a = gg( a, b, c, d, x[int(i+ 9)],  5, 568446438 );  // 25
                d = gg( d, a, b, c, x[int(i+14)],  9, -1019803690 );    // 26
                c = gg( c, d, a, b, x[int(i+ 3)], 14, -187363961 );     // 27
                b = gg( b, c, d, a, x[int(i+ 8)], 20, 1163531501 );     // 28
                a = gg( a, b, c, d, x[int(i+13)],  5, -1444681467 );    // 29
                d = gg( d, a, b, c, x[int(i+ 2)],  9, -51403784 );  // 30
                c = gg( c, d, a, b, x[int(i+ 7)], 14, 1735328473 );     // 31
                b = gg( b, c, d, a, x[int(i+12)], 20, -1926607734 );    // 32
               
                // Round 3
                a = hh( a, b, c, d, x[int(i+ 5)],  4, -378558 );    // 33
                d = hh( d, a, b, c, x[int(i+ 8)], 11, -2022574463 );    // 34
                c = hh( c, d, a, b, x[int(i+11)], 16, 1839030562 );     // 35
                b = hh( b, c, d, a, x[int(i+14)], 23, -35309556 );  // 36
                a = hh( a, b, c, d, x[int(i+ 1)],  4, -1530992060 );    // 37
                d = hh( d, a, b, c, x[int(i+ 4)], 11, 1272893353 );     // 38
                c = hh( c, d, a, b, x[int(i+ 7)], 16, -155497632 );     // 39
                b = hh( b, c, d, a, x[int(i+10)], 23, -1094730640 );    // 40
                a = hh( a, b, c, d, x[int(i+13)],  4, 681279174 );  // 41
                d = hh( d, a, b, c, x[int(i+ 0)], 11, -358537222 );     // 42
                c = hh( c, d, a, b, x[int(i+ 3)], 16, -722521979 );     // 43
                b = hh( b, c, d, a, x[int(i+ 6)], 23, 76029189 );   // 44
                a = hh( a, b, c, d, x[int(i+ 9)],  4, -640364487 );     // 45
                d = hh( d, a, b, c, x[int(i+12)], 11, -421815835 );     // 46
                c = hh( c, d, a, b, x[int(i+15)], 16, 530742520 );  // 47
                b = hh( b, c, d, a, x[int(i+ 2)], 23, -995338651 );     // 48
               
                // Round 4
                a = ii( a, b, c, d, x[int(i+ 0)],  6, -198630844 );     // 49
                d = ii( d, a, b, c, x[int(i+ 7)], 10, 1126891415 );     // 50
                c = ii( c, d, a, b, x[int(i+14)], 15, -1416354905 );    // 51
                b = ii( b, c, d, a, x[int(i+ 5)], 21, -57434055 );  // 52
                a = ii( a, b, c, d, x[int(i+12)],  6, 1700485571 );     // 53
                d = ii( d, a, b, c, x[int(i+ 3)], 10, -1894986606 );    // 54
                c = ii( c, d, a, b, x[int(i+10)], 15, -1051523 );   // 55
                b = ii( b, c, d, a, x[int(i+ 1)], 21, -2054922799 );    // 56
                a = ii( a, b, c, d, x[int(i+ 8)],  6, 1873313359 );     // 57
                d = ii( d, a, b, c, x[int(i+15)], 10, -30611744 );  // 58
                c = ii( c, d, a, b, x[int(i+ 6)], 15, -1560198380 );    // 59
                b = ii( b, c, d, a, x[int(i+13)], 21, 1309151649 );     // 60
                a = ii( a, b, c, d, x[int(i+ 4)],  6, -145523070 );     // 61
                d = ii( d, a, b, c, x[int(i+11)], 10, -1120210379 );    // 62
                c = ii( c, d, a, b, x[int(i+ 2)], 15, 718787259 );  // 63
                b = ii( b, c, d, a, x[int(i+ 9)], 21, -343485551 );     // 64

                a += aa;
                b += bb;
                c += cc;
                d += dd;
            }
            digest = new ByteArray()
            digest.writeInt(a);
            digest.writeInt(b);
            digest.writeInt(c);
            digest.writeInt(d);
            digest.position = 0;
            // Finish up by concatening the buffers with their hex output
            return IntUtil.toHex( a ) + IntUtil.toHex( b ) + IntUtil.toHex( c ) + IntUtil.toHex( d );
        }
       
        /**
         * Auxiliary function f as defined in RFC
         */

        private static function f( x:int, y:int, z:int ):int {
            return ( x & y ) | ( (~x) & z );
        }
       
        /**
         * Auxiliary function g as defined in RFC
         */

        private static function g( x:int, y:int, z:int ):int {
            return ( x & z ) | ( y & (~z) );
        }
       
        /**
         * Auxiliary function h as defined in RFC
         */

        private static function h( x:int, y:int, z:int ):int {
            return x ^ y ^ z;
        }
       
        /**
         * Auxiliary function i as defined in RFC
         */

        private static function i( x:int, y:int, z:int ):int {
            return y ^ ( x | (~z) );
        }
       
        /**
         * A generic transformation function.  The logic of ff, gg, hh, and
         * ii are all the same, minus the function used, so pull that logic
         * out and simplify the method bodies for the transoformation functions.
         */

        private static function transform( func:Function, a:int, b:int, c:int, d:int, x:int, s:int, t:int):int {
            var tmp:int = a + int( func( b, c, d ) ) + x + t;
            return IntUtil.rol( tmp, s ) +  b;
        }
       
        /**
         * ff transformation function
         */

        private static function ff ( a:int, b:int, c:int, d:int, x:int, s:int, t:int ):int {
            return transform( f, a, b, c, d, x, s, t );
        }
       
        /**
         * gg transformation function
         */

        private static function gg ( a:int, b:int, c:int, d:int, x:int, s:int, t:int ):int {
            return transform( g, a, b, c, d, x, s, t );
        }
       
        /**
         * hh transformation function
         */

        private static function hh ( a:int, b:int, c:int, d:int, x:int, s:int, t:int ):int {
            return transform( h, a, b, c, d, x, s, t );
        }
       
        /**
         * ii transformation function
         */

        private static function ii ( a:int, b:int, c:int, d:int, x:int, s:int, t:int ):int {
            return transform( i, a, b, c, d, x, s, t );
        }
       
        /**
         * Converts a string to a sequence of 16-word blocks
         * that we'll do the processing on.  Appends padding
         * and length in the process.
         *
         * @param s The string to split into blocks
         * @return An array containing the blocks that s was
         *          split into.
         */

        private static function createBlocks( s:ByteArray ):Array {
            var blocks:Array = new Array();
            var len:int = s.length * 8;
            var mask:int = 0xFF; // ignore hi byte of characters > 0xFF
            for( var i:int = 0; i < len; i += 8 ) {
                blocks[ int(i >> 5) ] |= ( s[ i / 8 ] & mask ) << ( i % 32 );
            }
           
            // append padding and length
            blocks[ int(len >> 5) ] |= 0x80 << ( len % 32 );
            blocks[ int(( ( ( len + 64 ) >>> 9 ) << 4 ) + 14) ] = len;
            return blocks;
        }
       
    }
}
?>

Have a fun ;)
Garry Lachman

JPEG Encoder ActionScript 3

Written by . Filed under ActionScript 3. Tagged , , , , , , , , , , , , , , . .

One more useful util from as3corelib.
Encode display object to JPEG ByteArray

BitString.as:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?
/*
  Copyright (c) 2008, Adobe Systems Incorporated
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are
  met:

  * Redistributions of source code must retain the above copyright notice,
    this list of conditions and the following disclaimer.
 
  * Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.
 
  * Neither the name of Adobe Systems Incorporated nor the names of its
    contributors may be used to endorse or promote products derived from
    this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

package com.adobe.images
{
    public class BitString
    {
        public var len:int = 0;
        public var val:int = 0;
    }
}
?>

JPGEncoder.as:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
<?
/*
  Copyright (c) 2008, Adobe Systems Incorporated
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are
  met:

  * Redistributions of source code must retain the above copyright notice,
    this list of conditions and the following disclaimer.
 
  * Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.
 
  * Neither the name of Adobe Systems Incorporated nor the names of its
    contributors may be used to endorse or promote products derived from
    this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

package com.adobe.images
{
    import flash.geom.*;
    import flash.display.*;
    import flash.utils.*;
   
    /**
     * Class that converts BitmapData into a valid JPEG
     */
   
    public class JPGEncoder
    {

        // Static table initialization
   
        private var ZigZag:Array = [
             0, 1, 5, 6,14,15,27,28,
             2, 4, 7,13,16,26,29,42,
             3, 8,12,17,25,30,41,43,
             9,11,18,24,31,40,44,53,
            10,19,23,32,39,45,52,54,
            20,22,33,38,46,51,55,60,
            21,34,37,47,50,56,59,61,
            35,36,48,49,57,58,62,63
        ];
   
        private var YTable:Array = new Array(64);
        private var UVTable:Array = new Array(64);
        private var fdtbl_Y:Array = new Array(64);
        private var fdtbl_UV:Array = new Array(64);
   
        private function initQuantTables(sf:int):void
        {
            var i:int;
            var t:Number;
            var YQT:Array = [
                16, 11, 10, 16, 24, 40, 51, 61,
                12, 12, 14, 19, 26, 58, 60, 55,
                14, 13, 16, 24, 40, 57, 69, 56,
                14, 17, 22, 29, 51, 87, 80, 62,
                18, 22, 37, 56, 68,109,103, 77,
                24, 35, 55, 64, 81,104,113, 92,
                49, 64, 78, 87,103,121,120,101,
                72, 92, 95, 98,112,100,103, 99
            ];
            for (i = 0; i < 64; i++) {
                t = Math.floor((YQT[i]*sf+50)/100);
                if (t < 1) {
                    t = 1;
                } else if (t > 255) {
                    t = 255;
                }
                YTable[ZigZag[i]] = t;
            }
            var UVQT:Array = [
                17, 18, 24, 47, 99, 99, 99, 99,
                18, 21, 26, 66, 99, 99, 99, 99,
                24, 26, 56, 99, 99, 99, 99, 99,
                47, 66, 99, 99, 99, 99, 99, 99,
                99, 99, 99, 99, 99, 99, 99, 99,
                99, 99, 99, 99, 99, 99, 99, 99,
                99, 99, 99, 99, 99, 99, 99, 99,
                99, 99, 99, 99, 99, 99, 99, 99
            ];
            for (i = 0; i < 64; i++) {
                t = Math.floor((UVQT[i]*sf+50)/100);
                if (t < 1) {
                    t = 1;
                } else if (t > 255) {
                    t = 255;
                }
                UVTable[ZigZag[i]] = t;
            }
            var aasf:Array = [
                1.0, 1.387039845, 1.306562965, 1.175875602,
                1.0, 0.785694958, 0.541196100, 0.275899379
            ];
            i = 0;
            for (var row:int = 0; row < 8; row++)
            {
                for (var col:int = 0; col < 8; col++)
                {
                    fdtbl_Y[i]  = (1.0 / (YTable [ZigZag[i]] * aasf[row] * aasf[col] * 8.0));
                    fdtbl_UV[i] = (1.0 / (UVTable[ZigZag[i]] * aasf[row] * aasf[col] * 8.0));
                    i++;
                }
            }
        }
   
        private var YDC_HT:Array;
        private var UVDC_HT:Array;
        private var YAC_HT:Array;
        private var UVAC_HT:Array;
   
        private function computeHuffmanTbl(nrcodes:Array, std_table:Array):Array
        {
            var codevalue:int = 0;
            var pos_in_table:int = 0;
            var HT:Array = new Array();
            for (var k:int=1; k<=16; k++) {
                for (var j:int=1; j<=nrcodes[k]; j++) {
                    HT[std_table[pos_in_table]] = new BitString();
                    HT[std_table[pos_in_table]].val = codevalue;
                    HT[std_table[pos_in_table]].len = k;
                    pos_in_table++;
                    codevalue++;
                }
                codevalue*=2;
            }
            return HT;
        }
   
        private var std_dc_luminance_nrcodes:Array = [0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0];
        private var std_dc_luminance_values:Array = [0,1,2,3,4,5,6,7,8,9,10,11];
        private var std_ac_luminance_nrcodes:Array = [0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d];
        private var std_ac_luminance_values:Array = [
            0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,
            0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07,
            0x22,0x71,0x14,0x32,0x81,0x91,0xa1,0x08,
            0x23,0x42,0xb1,0xc1,0x15,0x52,0xd1,0xf0,
            0x24,0x33,0x62,0x72,0x82,0x09,0x0a,0x16,
            0x17,0x18,0x19,0x1a,0x25,0x26,0x27,0x28,
            0x29,0x2a,0x34,0x35,0x36,0x37,0x38,0x39,
            0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,
            0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59,
            0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,
            0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,
            0x7a,0x83,0x84,0x85,0x86,0x87,0x88,0x89,
            0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,
            0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,
            0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6,
            0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,
            0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,
            0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe1,0xe2,
            0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,
            0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,
            0xf9,0xfa
        ];
   
        private var std_dc_chrominance_nrcodes:Array = [0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0];
        private var std_dc_chrominance_values:Array = [0,1,2,3,4,5,6,7,8,9,10,11];
        private var std_ac_chrominance_nrcodes:Array = [0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77];
        private var std_ac_chrominance_values:Array = [
            0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,
            0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,
            0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91,
            0xa1,0xb1,0xc1,0x09,0x23,0x33,0x52,0xf0,
            0x15,0x62,0x72,0xd1,0x0a,0x16,0x24,0x34,
            0xe1,0x25,0xf1,0x17,0x18,0x19,0x1a,0x26,
            0x27,0x28,0x29,0x2a,0x35,0x36,0x37,0x38,
            0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,
            0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58,
            0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,
            0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,
            0x79,0x7a,0x82,0x83,0x84,0x85,0x86,0x87,
            0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96,
            0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,
            0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,
            0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,
            0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,
            0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,
            0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,
            0xea,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,
            0xf9,0xfa
        ];
   
        private function initHuffmanTbl():void
        {
            YDC_HT = computeHuffmanTbl(std_dc_luminance_nrcodes,std_dc_luminance_values);
            UVDC_HT = computeHuffmanTbl(std_dc_chrominance_nrcodes,std_dc_chrominance_values);
            YAC_HT = computeHuffmanTbl(std_ac_luminance_nrcodes,std_ac_luminance_values);
            UVAC_HT = computeHuffmanTbl(std_ac_chrominance_nrcodes,std_ac_chrominance_values);
        }
   
        private var bitcode:Array = new Array(65535);
        private var category:Array = new Array(65535);
   
        private function initCategoryNumber():void
        {
            var nrlower:int = 1;
            var nrupper:int = 2;
            var nr:int;
            for (var cat:int=1; cat<=15; cat++) {
                //Positive numbers
                for (nr=nrlower; nr<nrupper; nr++) {
                    category[32767+nr] = cat;
                    bitcode[32767+nr] = new BitString();
                    bitcode[32767+nr].len = cat;
                    bitcode[32767+nr].val = nr;
                }
                //Negative numbers
                for (nr=-(nrupper-1); nr<=-nrlower; nr++) {
                    category[32767+nr] = cat;
                    bitcode[32767+nr] = new BitString();
                    bitcode[32767+nr].len = cat;
                    bitcode[32767+nr].val = nrupper-1+nr;
                }
                nrlower <<= 1;
                nrupper <<= 1;
            }
        }
   
        // IO functions
   
        private var byteout:ByteArray;
        private var bytenew:int = 0;
        private var bytepos:int = 7;
   
        private function writeBits(bs:BitString):void
        {
            var value:int = bs.val;
            var posval:int = bs.len-1;
            while ( posval >= 0 ) {
                if (value & uint(1 << posval) ) {
                    bytenew |= uint(1 << bytepos);
                }
                posval--;
                bytepos--;
                if (bytepos < 0) {
                    if (bytenew == 0xFF) {
                        writeByte(0xFF);
                        writeByte(0);
                    }
                    else {
                        writeByte(bytenew);
                    }
                    bytepos=7;
                    bytenew=0;
                }
            }
        }
   
        private function writeByte(value:int):void
        {
            byteout.writeByte(value);
        }
   
        private function writeWord(value:int):void
        {
            writeByte((value>>8)&0xFF);
            writeByte((value   )&0xFF);
        }
   
        // DCT & quantization core
   
        private function fDCTQuant(data:Array, fdtbl:Array):Array
        {
            var tmp0:Number, tmp1:Number, tmp2:Number, tmp3:Number, tmp4:Number, tmp5:Number, tmp6:Number, tmp7:Number;
            var tmp10:Number, tmp11:Number, tmp12:Number, tmp13:Number;
            var z1:Number, z2:Number, z3:Number, z4:Number, z5:Number, z11:Number, z13:Number;
            var i:int;
            /* Pass 1: process rows. */
            var dataOff:int=0;
            for (i=0; i<8; i++) {
                tmp0 = data[dataOff+0] + data[dataOff+7];
                tmp7 = data[dataOff+0] - data[dataOff+7];
                tmp1 = data[dataOff+1] + data[dataOff+6];
                tmp6 = data[dataOff+1] - data[dataOff+6];
                tmp2 = data[dataOff+2] + data[dataOff+5];
                tmp5 = data[dataOff+2] - data[dataOff+5];
                tmp3 = data[dataOff+3] + data[dataOff+4];
                tmp4 = data[dataOff+3] - data[dataOff+4];
   
                /* Even part */
                tmp10 = tmp0 + tmp3;    /* phase 2 */
                tmp13 = tmp0 - tmp3;
                tmp11 = tmp1 + tmp2;
                tmp12 = tmp1 - tmp2;
   
                data[dataOff+0] = tmp10 + tmp11; /* phase 3 */
                data[dataOff+4] = tmp10 - tmp11;
   
                z1 = (tmp12 + tmp13) * 0.707106781; /* c4 */
                data[dataOff+2] = tmp13 + z1; /* phase 5 */
                data[dataOff+6] = tmp13 - z1;
   
                /* Odd part */
                tmp10 = tmp4 + tmp5; /* phase 2 */
                tmp11 = tmp5 + tmp6;
                tmp12 = tmp6 + tmp7;
   
                /* The rotator is modified from fig 4-8 to avoid extra negations. */
                z5 = (tmp10 - tmp12) * 0.382683433; /* c6 */
                z2 = 0.541196100 * tmp10 + z5; /* c2-c6 */
                z4 = 1.306562965 * tmp12 + z5; /* c2+c6 */
                z3 = tmp11 * 0.707106781; /* c4 */
   
                z11 = tmp7 + z3;    /* phase 5 */
                z13 = tmp7 - z3;
   
                data[dataOff+5] = z13 + z2; /* phase 6 */
                data[dataOff+3] = z13 - z2;
                data[dataOff+1] = z11 + z4;
                data[dataOff+7] = z11 - z4;
   
                dataOff += 8; /* advance pointer to next row */
            }
   
            /* Pass 2: process columns. */
            dataOff = 0;
            for (i=0; i<8; i++) {
                tmp0 = data[dataOff+ 0] + data[dataOff+56];
                tmp7 = data[dataOff+ 0] - data[dataOff+56];
                tmp1 = data[dataOff+ 8] + data[dataOff+48];
                tmp6 = data[dataOff+ 8] - data[dataOff+48];
                tmp2 = data[dataOff+16] + data[dataOff+40];
                tmp5 = data[dataOff+16] - data[dataOff+40];
                tmp3 = data[dataOff+24] + data[dataOff+32];
                tmp4 = data[dataOff+24] - data[dataOff+32];
   
                /* Even part */
                tmp10 = tmp0 + tmp3;    /* phase 2 */
                tmp13 = tmp0 - tmp3;
                tmp11 = tmp1 + tmp2;
                tmp12 = tmp1 - tmp2;
   
                data[dataOff+ 0] = tmp10 + tmp11; /* phase 3 */
                data[dataOff+32] = tmp10 - tmp11;
   
                z1 = (tmp12 + tmp13) * 0.707106781; /* c4 */
                data[dataOff+16] = tmp13 + z1; /* phase 5 */
                data[dataOff+48] = tmp13 - z1;
   
                /* Odd part */
                tmp10 = tmp4 + tmp5; /* phase 2 */
                tmp11 = tmp5 + tmp6;
                tmp12 = tmp6 + tmp7;
   
                /* The rotator is modified from fig 4-8 to avoid extra negations. */
                z5 = (tmp10 - tmp12) * 0.382683433; /* c6 */
                z2 = 0.541196100 * tmp10 + z5; /* c2-c6 */
                z4 = 1.306562965 * tmp12 + z5; /* c2+c6 */
                z3 = tmp11 * 0.707106781; /* c4 */
   
                z11 = tmp7 + z3;    /* phase 5 */
                z13 = tmp7 - z3;
   
                data[dataOff+40] = z13 + z2; /* phase 6 */
                data[dataOff+24] = z13 - z2;
                data[dataOff+ 8] = z11 + z4;
                data[dataOff+56] = z11 - z4;
   
                dataOff++; /* advance pointer to next column */
            }
   
            // Quantize/descale the coefficients
            for (i=0; i<64; i++) {
                // Apply the quantization and scaling factor & Round to nearest integer
                data[i] = Math.round((data[i]*fdtbl[i]));
            }
            return data;
        }
   
        // Chunk writing
   
        private function writeAPP0():void
        {
            writeWord(0xFFE0); // marker
            writeWord(16); // length
            writeByte(0x4A); // J
            writeByte(0x46); // F
            writeByte(0x49); // I
            writeByte(0x46); // F
            writeByte(0); // = "JFIF",'\0'
            writeByte(1); // versionhi
            writeByte(1); // versionlo
            writeByte(0); // xyunits
            writeWord(1); // xdensity
            writeWord(1); // ydensity
            writeByte(0); // thumbnwidth
            writeByte(0); // thumbnheight
        }
   
        private function writeSOF0(width:int, height:int):void
        {
            writeWord(0xFFC0); // marker
            writeWord(17);   // length, truecolor YUV JPG
            writeByte(8);    // precision
            writeWord(height);
            writeWord(width);
            writeByte(3);    // nrofcomponents
            writeByte(1);    // IdY
            writeByte(0x11); // HVY
            writeByte(0);    // QTY
            writeByte(2);    // IdU
            writeByte(0x11); // HVU
            writeByte(1);    // QTU
            writeByte(3);    // IdV
            writeByte(0x11); // HVV
            writeByte(1);    // QTV
        }
   
        private function writeDQT():void
        {
            writeWord(0xFFDB); // marker
            writeWord(132);    // length
            writeByte(0);
            var i:int;
            for (i=0; i<64; i++) {
                writeByte(YTable[i]);
            }
            writeByte(1);
            for (i=0; i<64; i++) {
                writeByte(UVTable[i]);
            }
        }
   
        private function writeDHT():void
        {
            writeWord(0xFFC4); // marker
            writeWord(0x01A2); // length
            var i:int;
   
            writeByte(0); // HTYDCinfo
            for (i=0; i<16; i++) {
                writeByte(std_dc_luminance_nrcodes[i+1]);
            }
            for (i=0; i<=11; i++) {
                writeByte(std_dc_luminance_values[i]);
            }
   
            writeByte(0x10); // HTYACinfo
            for (i=0; i<16; i++) {
                writeByte(std_ac_luminance_nrcodes[i+1]);
            }
            for (i=0; i<=161; i++) {
                writeByte(std_ac_luminance_values[i]);
            }
   
            writeByte(1); // HTUDCinfo
            for (i=0; i<16; i++) {
                writeByte(std_dc_chrominance_nrcodes[i+1]);
            }
            for (i=0; i<=11; i++) {
                writeByte(std_dc_chrominance_values[i]);
            }
   
            writeByte(0x11); // HTUACinfo
            for (i=0; i<16; i++) {
                writeByte(std_ac_chrominance_nrcodes[i+1]);
            }
            for (i=0; i<=161; i++) {
                writeByte(std_ac_chrominance_values[i]);
            }
        }
   
        private function writeSOS():void
        {
            writeWord(0xFFDA); // marker
            writeWord(12); // length
            writeByte(3); // nrofcomponents
            writeByte(1); // IdY
            writeByte(0); // HTY
            writeByte(2); // IdU
            writeByte(0x11); // HTU
            writeByte(3); // IdV
            writeByte(0x11); // HTV
            writeByte(0); // Ss
            writeByte(0x3f); // Se
            writeByte(0); // Bf
        }
   
        // Core processing
        private var DU:Array = new Array(64);
   
        private function processDU(CDU:Array, fdtbl:Array, DC:Number, HTDC:Array, HTAC:Array):Number
        {
            var EOB:BitString = HTAC[0x00];
            var M16zeroes:BitString = HTAC[0xF0];
            var i:int;
   
            var DU_DCT:Array = fDCTQuant(CDU, fdtbl);
            //ZigZag reorder
            for (i=0;i<64;i++) {
                DU[ZigZag[i]]=DU_DCT[i];
            }
            var Diff:int = DU[0] - DC; DC = DU[0];
            //Encode DC
            if (Diff==0) {
                writeBits(HTDC[0]); // Diff might be 0
            } else {
                writeBits(HTDC[category[32767+Diff]]);
                writeBits(bitcode[32767+Diff]);
            }
            //Encode ACs
            var end0pos:int = 63;
            for (; (end0pos>0)&&(DU[end0pos]==0); end0pos--) {
            };
            //end0pos = first element in reverse order !=0
            if ( end0pos == 0) {
                writeBits(EOB);
                return DC;
            }
            i = 1;
            while ( i <= end0pos ) {
                var startpos:int = i;
                for (; (DU[i]==0) && (i<=end0pos); i++) {
                }
                var nrzeroes:int = i-startpos;
                if ( nrzeroes >= 16 ) {
                    for (var nrmarker:int=1; nrmarker <= nrzeroes/16; nrmarker++) {
                        writeBits(M16zeroes);
                    }
                    nrzeroes = int(nrzeroes&0xF);
                }
                writeBits(HTAC[nrzeroes*16+category[32767+DU[i]]]);
                writeBits(bitcode[32767+DU[i]]);
                i++;
            }
            if ( end0pos != 63 ) {
                writeBits(EOB);
            }
            return DC;
        }
   
        private var YDU:Array = new Array(64);
        private var UDU:Array = new Array(64);
        private var VDU:Array = new Array(64);
   
        private function RGB2YUV(img:BitmapData, xpos:int, ypos:int):void
        {
            var pos:int=0;
            for (var y:int=0; y<8; y++) {
                for (var x:int=0; x<8; x++) {
                    var P:uint = img.getPixel32(xpos+x,ypos+y);
                    var R:Number = Number((P>>16)&0xFF);
                    var G:Number = Number((P>> 8)&0xFF);
                    var B:Number = Number((P    )&0xFF);
                    YDU[pos]=((( 0.29900)*R+( 0.58700)*G+( 0.11400)*B))-128;
                    UDU[pos]=(((-0.16874)*R+(-0.33126)*G+( 0.50000)*B));
                    VDU[pos]=((( 0.50000)*R+(-0.41869)*G+(-0.08131)*B));
                    pos++;
                }
            }
        }
   
        /**
         * Constructor for JPEGEncoder class
         *
         * @param quality The quality level between 1 and 100 that detrmines the
         * level of compression used in the generated JPEG
         * @langversion ActionScript 3.0
         * @playerversion Flash 9.0
         * @tiptext
         */
   
        public function JPGEncoder(quality:Number = 50)
        {
            if (quality <= 0) {
                quality = 1;
            }
            if (quality > 100) {
                quality = 100;
            }
            var sf:int = 0;
            if (quality < 50) {
                sf = int(5000 / quality);
            } else {
                sf = int(200 - quality*2);
            }
            // Create tables
            initHuffmanTbl();
            initCategoryNumber();
            initQuantTables(sf);
        }
   
        /**
         * Created a JPEG image from the specified BitmapData
         *
         * @param image The BitmapData that will be converted into the JPEG format.
         * @return a ByteArray representing the JPEG encoded image data.
         * @langversion ActionScript 3.0
         * @playerversion Flash 9.0
         * @tiptext
         */

        public function encode(image:BitmapData):ByteArray
        {
            // Initialize bit writer
            byteout = new ByteArray();
            bytenew=0;
            bytepos=7;
   
            // Add JPEG headers
            writeWord(0xFFD8); // SOI
            writeAPP0();
            writeDQT();
            writeSOF0(image.width,image.height);
            writeDHT();
            writeSOS();

   
            // Encode 8x8 macroblocks
            var DCY:Number=0;
            var DCU:Number=0;
            var DCV:Number=0;
            bytenew=0;
            bytepos=7;
            for (var ypos:int=0; ypos<image.height; ypos+=8) {
                for (var xpos:int=0; xpos<image.width; xpos+=8) {
                    RGB2YUV(image, xpos, ypos);
                    DCY = processDU(YDU, fdtbl_Y, DCY, YDC_HT, YAC_HT);
                    DCU = processDU(UDU, fdtbl_UV, DCU, UVDC_HT, UVAC_HT);
                    DCV = processDU(VDU, fdtbl_UV, DCV, UVDC_HT, UVAC_HT);
                }
            }
   
            // Do the bit alignment of the EOI marker
            if ( bytepos >= 0 ) {
                var fillbits:BitString = new BitString();
                fillbits.len = bytepos+1;
                fillbits.val = (1<<(bytepos+1))-1;
                writeBits(fillbits);
            }
   
            writeWord(0xFFD9); //EOI
            return byteout;
        }
    }
}
?>

Have a nice day ;)
Garry Lachman

PNG Encoder in ActionScript 3

Written by . Filed under ActionScript 3. Tagged , , , , , , , , , , , , . .

ActionScript 3 PNG Encoder class, for exporting display objects into PNG ByteArray….
Taken from as3corelib project.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
<?
/*
  Copyright (c) 2008, Adobe Systems Incorporated
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are
  met:

  * Redistributions of source code must retain the above copyright notice,
    this list of conditions and the following disclaimer.
 
  * Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.
 
  * Neither the name of Adobe Systems Incorporated nor the names of its
    contributors may be used to endorse or promote products derived from
    this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

package
{
    import flash.geom.*;
    import flash.display.Bitmap;
    import flash.display.BitmapData;
    import flash.utils.ByteArray;

    /**
     * Class that converts BitmapData into a valid PNG
     */

    public class PNGEncoder
    {
        /**
         * Created a PNG image from the specified BitmapData
         *
         * @param image The BitmapData that will be converted into the PNG format.
         * @return a ByteArray representing the PNG encoded image data.
         * @langversion ActionScript 3.0
         * @playerversion Flash 9.0
         * @tiptext
         */
       
        public static function encode(img:BitmapData):ByteArray {
            // Create output byte array
            var png:ByteArray = new ByteArray();
            // Write PNG signature
            png.writeUnsignedInt(0x89504e47);
            png.writeUnsignedInt(0x0D0A1A0A);
            // Build IHDR chunk
            var IHDR:ByteArray = new ByteArray();
            IHDR.writeInt(img.width);
            IHDR.writeInt(img.height);
            IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA
            IHDR.writeByte(0);
            writeChunk(png,0x49484452,IHDR);
            // Build IDAT chunk
            var IDAT:ByteArray= new ByteArray();
            for(var i:int=0;i < img.height;i++) {
                // no filter
                IDAT.writeByte(0);
                var p:uint;
                var j:int;
                if ( !img.transparent ) {
                    for(j=0;j < img.width;j++) {
                        p = img.getPixel(j,i);
                        IDAT.writeUnsignedInt(
                            uint(((p&0xFFFFFF) << 8)|0xFF));
                    }
                } else {
                    for(j=0;j < img.width;j++) {
                        p = img.getPixel32(j,i);
                        IDAT.writeUnsignedInt(
                            uint(((p&0xFFFFFF) << 8)|
                            (p>>>24)));
                    }
                }
            }
            IDAT.compress();
            writeChunk(png,0x49444154,IDAT);
            // Build IEND chunk
            writeChunk(png,0x49454E44,null);
            // return PNG
            return png;
        }
   
        private static var crcTable:Array;
        private static var crcTableComputed:Boolean = false;
   
        private static function writeChunk(png:ByteArray,
                type:uint, data:ByteArray):void {
            if (!crcTableComputed) {
                crcTableComputed = true;
                crcTable = [];
                var c:uint;
                for (var n:uint = 0; n < 256; n++) {
                    c = n;
                    for (var k:uint = 0; k < 8; k++) {
                        if (c & 1) {
                            c = uint(uint(0xedb88320) ^
                                uint(c >>> 1));
                        } else {
                            c = uint(c >>> 1);
                        }
                    }
                    crcTable[n] = c;
                }
            }
            var len:uint = 0;
            if (data != null) {
                len = data.length;
            }
            png.writeUnsignedInt(len);
            var p:uint = png.position;
            png.writeUnsignedInt(type);
            if ( data != null ) {
                png.writeBytes(data);
            }
            var e:uint = png.position;
            png.position = p;
            c = 0xffffffff;
            for (var i:int = 0; i < (e-p); i++) {
                c = uint(crcTable[
                    (c ^ png.readUnsignedByte()) &
                    uint(0xff)] ^ uint(c >>> 8));
            }
            c = uint(c^uint(0xffffffff));
            png.position = e;
            png.writeUnsignedInt(c);
        }
    }
}
?>

Have a fun !!!
Garry Lachman

Base64 Encoding Class in ActionScript 3

Written by . Filed under ActionScript 3. Tagged , , , , , , , , , , , . .

This is a class for Base64 Encoding by Steve Webster…
Very Usefull one!!!

Base64.as

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
package {
/*
Base64 - 1.1.0

Copyright (c) 2006 Steve Webster

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/


package {

        import flash.utils.ByteArray;
       
        public class Base64 {
               
                private static const BASE64_CHARS:String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

                public static const version:String = "1.1.0";

                public static function encode(data:String):String {
                        // Convert string to ByteArray
                        var bytes:ByteArray = new ByteArray();
                        bytes.writeUTFBytes(data);
                       
                        // Return encoded ByteArray
                        return encodeByteArray(bytes);
                }
               
                public static function encodeByteArray(data:ByteArray):String {
                        // Initialise output
                        var output:String = "";
                       
                        // Create data and output buffers
                        var dataBuffer:Array;
                        var outputBuffer:Array = new Array(4);
                       
                        // Rewind ByteArray
                        data.position = 0;
                       
                        // while there are still bytes to be processed
                        while (data.bytesAvailable > 0) {
                                // Create new data buffer and populate next 3 bytes from data
                                dataBuffer = new Array();
                                for (var i:uint = 0; i < 3 && data.bytesAvailable > 0; i++) {
                                        dataBuffer[i] = data.readUnsignedByte();
                                }
                               
                                // Convert to data buffer Base64 character positions and
                                // store in output buffer
                                outputBuffer[0] = (dataBuffer[0] & 0xfc) >> 2;
                                outputBuffer[1] = ((dataBuffer[0] & 0x03) << 4) | ((dataBuffer[1]) >> 4);
                                outputBuffer[2] = ((dataBuffer[1] & 0x0f) << 2) | ((dataBuffer[2]) >> 6);
                                outputBuffer[3] = dataBuffer[2] & 0x3f;
                               
                                // If data buffer was short (i.e not 3 characters) then set
                                // end character indexes in data buffer to index of '=' symbol.
                                // This is necessary because Base64 data is always a multiple of
                                // 4 bytes and is basses with '=' symbols.
                                for (var j:uint = dataBuffer.length; j < 3; j++) {
                                        outputBuffer[j + 1] = 64;
                                }
                               
                                // Loop through output buffer and add Base64 characters to
                                // encoded data string for each character.
                                for (var k:uint = 0; k < outputBuffer.length; k++) {
                                        output += BASE64_CHARS.charAt(outputBuffer[k]);
                                }
                        }
                       
                        // Return encoded data
                        return output;
                }
               
                public static function decode(data:String):String {
                        // Decode data to ByteArray
                        var bytes:ByteArray = decodeToByteArray(data);
                       
                        // Convert to string and return
                        return bytes.readUTFBytes(bytes.length);
                }
               
                public static function decodeToByteArray(data:String):ByteArray {
                        // Initialise output ByteArray for decoded data
                        var output:ByteArray = new ByteArray();
                       
                        // Create data and output buffers
                        var dataBuffer:Array = new Array(4);
                        var outputBuffer:Array = new Array(3);

                        // While there are data bytes left to be processed
                        for (var i:uint = 0; i < data.length; i += 4) {
                                // Populate data buffer with position of Base64 characters for
                                // next 4 bytes from encoded data
                                for (var j:uint = 0; j < 4 && i + j < data.length; j++) {
                                        dataBuffer[j] = BASE64_CHARS.indexOf(data.charAt(i + j));
                                }
                       
                        // Decode data buffer back into bytes
                                outputBuffer[0] = (dataBuffer[0] << 2) + ((dataBuffer[1] & 0x30) >> 4);
                                outputBuffer[1] = ((dataBuffer[1] & 0x0f) << 4) + ((dataBuffer[2] & 0x3c) >> 2);                
                                outputBuffer[2] = ((dataBuffer[2] & 0x03) << 6) + dataBuffer[3];
                               
                                // Add all non-padded bytes in output buffer to decoded data
                                for (var k:uint = 0; k < outputBuffer.length; k++) {
                                        if (dataBuffer[k+1] == 64) break;
                                        output.writeByte(outputBuffer[k]);
                                }
                        }
                       
                        // Rewind decoded data ByteArray
                        output.position = 0;
                       
                        // Return decoded data
                        return output;
                }
               
                public function Base64() {
                        throw new Error("Base64 class is static container only");
                }
        }
}

Useage:

1
2
3
4
5
var aString:String = "to Convert";
trace(Base64.encode(aString)); // Base64 String

var aBase64:String = "dG8gQ29udmVydA==";
trace(Base64.decode(aBase64)) // Original String

Have Fun ;)

Get Vars from URL string in ActionScript 3

Written by . Filed under ActionScript 3. Tagged , , . .

The function is break the string into param name and param value of the URL.
if we have URL like http://garry-lachman.com/index.php?name1=value1&test=10

The function will return array:
Array["name1"] = “value1″;
Array["test"] = “10”;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public function getParamsFromURL(fullurl:String):Array
{
    var params:Array = fullurl.split('?');
    fullurl = params[1];
    params = fullurl.split('&');
    var length:uint = params.length;
    var g:uint;
    for (g=0; g< length; g++){
        var index:int=0;
        var kvPair:String = params[g];
        if((index = kvPair.indexOf("=")) > 0){
            var key:String = kvPair.substring(0,index);
            var value:String = kvPair.substring(index+1);
            params[key] = value;
        }
    }
    return params;
}

Have Fun ;)
Garry Lachman

Table Engine in ActionScript 3

Written by . Filed under ActionScript 3. Tagged , , , , , , , , . .

I write this Table Enigne for easy making of data forms, data view in easy
use like Tables in HTML that can contain any DisplayObject.

TableEngineItem.as:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package layout.Engines
{
/**
* ...
* @author Garry Lachman
*/


import flash.display.DisplayObject;
import flash.display.Sprite;

public class TableEngineItem extends Sprite
{
private var aParams:Object;
private var aDisplayObject:DisplayObject

public function TableEngineItem(_sprite:DisplayObject, _params:Object=null)
{
this.aDisplayObject = _sprite;
this.addChild(this.aDisplayObject);

if (_params!=null)
this.aParams = _params;
}

public function set Params(_params:Object):void             {   this.aParams = _params;     }
public function get Params():Object                         {   return this.aParams         }
public function get DisplayObjectInstance():DisplayObject   {   return this.aDisplayObject  }

override public function get width():Number{return this.aDisplayObject.width;}
override public function get height():Number{return this.aDisplayObject.height;}
}

}

TableEngine.as:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
package layout.Engines
{
import flash.display.Sprite;
import layout.Engines.TableEngineItem
import flash.text.TextField;

public class TableEngine extends Sprite
{
public static const DIRECTION_LTR:String = "dirLTR";
public static const DIRECTION_RTL:String = "dirRTL";
public static const DIRECTION_CENTER:String = "dirCenter";

private var direction:String;

private var aTable:Array;
private var aContainer:Sprite;

private var contentHeight:Number;
private var contentWidth:Number;

public function TableEngine(_cells:int, _direction:String="dirLTR")
{
this.direction = _direction;
this.aTable = new Array();

for (var i:int=0; i &lt; _cells; i++)
aTable.push(new Array());

this.aContainer = new Sprite();
this.addChild(this.aContainer);
}

/**
* @param _cell
* @param _row
* @param _displayObject
* Adding an Element to the table
*/

public function AddElement(_cell:int, _row:int, _tableItem:TableEngineItem):void
{
if (_tableItem == null)
return;

trace("ADDING ELEMENT to " + _cell + " , " + _row);
if (this.aTable[_cell] == null)
throw new Error("Cell need to be added at the constractor");

this.aTable[_cell][_row] = _tableItem;
}

/**
*   Render the table, first of all check the max X and max Y then
*  Render the Display
*/

public function Render():void
{
/* Calculat the maximum X and maximum Y */
// Max X Per Cell.
var maxX:Array = [];
// Max Y Per Row.
var maxY:Array = [];

var maxTopX:Number = 0;

// Loop the Cell Array.
for each (var i:Array in this.aTable)
{
trace("work on: " + this.aTable.indexOf(i));
// Loop the Row Array.
for each (var ii:TableEngineItem in i)
{
if (ii == null)
continue;

trace("parse: " + ii + ", index: " + i.indexOf(ii));
// Check if maxX element for cell is not null... if its null set 0.
if (maxX[this.aTable.indexOf(i)] == null)
maxX[this.aTable.indexOf(i)] = 0;

// Check if the DisplayObject width of this row is bigger then maxX element
// for this cell... if true then set it to maxX
// * Check if the index is not 0, the first element must be 0.
if (ii.width &gt; maxX[this.aTable.indexOf(i)] &amp;&amp; this.aTable.indexOf(i) &gt; 0)
maxX[this.aTable.indexOf(i)] = ii.width;

trace("maxX["+this.aTable.indexOf(i)+"]:" + maxX[this.aTable.indexOf(i)]);

if ((maxX[this.aTable.indexOf(i)] + ii.width) &gt; maxTopX &amp;&amp; this.aTable.indexOf(i) == this.aTable.length-1)
{
maxTopX = (maxX[this.aTable.indexOf(i)] + ii.width);
trace("set new maxTopX:" + maxTopX + ", ii.width:" + ii.width   );
}

// Check if maxY element for row is not null... if its null set 0.
if (maxY[i.indexOf(ii)] == null)
maxY[i.indexOf(ii)] = 0;

// Check if the DisplayObject height of this row is bigger then maxY element
// for this row... if true then set it to maxY.
if (ii.height &gt; maxY[i.indexOf(ii)])
maxY[i.indexOf(ii)] = ii.height;
}
}

// Loop all over cells maxX and calc the start X refer to all table
for (var a:int; a &lt; maxX.length; a++)
{
if (maxX[a-1] != null)
maxX[a] = maxX[a] + maxX[a - 1];
}

for (var aa:int; aa &lt; maxY.length; aa++)
if (maxY[aa-1] != null)
maxY[aa] = maxY[aa] + maxY[aa-1];

// setting first element @ 0 position
maxY.unshift(0);

/* Render The Graphics */
for each (var b:Array in this.aTable)
{
trace("work on: " + this.aTable.indexOf(b));
// Loop the Row Array.
for each (var bb:TableEngineItem in b)
{
// adding to DisplayList and setting x and y

this.aContainer.addChild(bb);

if (this.direction == TableEngine.DIRECTION_RTL)
{
if (maxX[this.aTable.indexOf(b)+1] != null)
bb.x = maxX[this.aTable.indexOf(b) + 1] - bb.DisplayObjectInstance.width;
else
bb.x = maxTopX - bb.DisplayObjectInstance.width;
}
else if (this.direction == TableEngine.DIRECTION_CENTER)
{
bb.x = maxX[this.aTable.indexOf(b)]
}
else
{
bb.x = maxX[this.aTable.indexOf(b)]
}
bb.y = maxY[b.indexOf(bb)];
this.contentHeight = bb.y + bb.height;
this.contentWidth = bb.x + bb.width;
}
}
}

override public function get height():Number    {       return this.contentHeight;      }
override public function get width():Number {       return this.contentWidth;       }

/**
*   Delete All elements and clear the data
*/

public function Clear(_cells:int):void
{
for (var i:int=this.aContainer.numChildren-1; i &gt; -1; i--)
{
this.aContainer.removeChildAt(i);
}

this.aTable = new Array();

for (var ii:int=0; ii &lt; _cells; ii++)
aTable.push(new Array());
}

public function GetLength(_cell:int):int
{
return (this.aTable[_cell] as Array).length;
}

public function GetItem(_cell:int, _i:int):TableEngineItem
{
return (this.aTable[_cell] as Array)[_i];
}

public function GetItemsInCell(_cell:int):Array
{
return (this.aTable[_cell] as Array);
}

public function get Container():Sprite
{
return this.aContainer;
}

public function DeleteItemByDS(_ds:*):void
{
for each (var i:Array in this.aTable)
{
// Loop the Row Array.
for each (var ii:TableEngineItem in i)
{
if (ii.DisplayObjectInstance == _ds)
{
this.aContainer.removeChild(ii);
i.splice(i.indexOf(ii),1);
}
}
}
}
}
}

Usage:

1
2
3
4
5
6
7
8
9
10
11
12
var table: TableEngine = new TableEngine(2,TableEngine.DIRECTION_RTL);
addChild(table);

// first row
table.AddElement(0, table.GetLength(0), new TableEngineItem([DisplayObject]));
table.AddElement(1, table.GetLength(1), new TableEngineItem([DisplayObject]));

// secound row
table.AddElement(0, table.GetLength(0), new TableEngineItem([DisplayObject]));
table.AddElement(1, table.GetLength(1), new TableEngineItem([DisplayObject]));

table.Render();

FMS blocked port detection – ActionScript 3

Written by . Filed under ActionScript 3. Tagged , , , , , , , , , , , . .

FMS block port detection – ActionScript 3

The fms port (1935) closed on many office firewalls, the problem
is that flash had 30 sec timeout before tunnle it to port 80.
Becouse that i write little script that use socket object to test the
port and tunnle it to http when port 1935 is closed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package
{
import flash.events.Event;
import flash.net.Socket;
import flash.events.IOErrorEvent
import flash.events.SecurityErrorEvent

/**
* @author Garry Lachman
*
* Usage:
* FMSPortTester.TestPorts(onSuccess)
* function onSuccess(_fmsURL:String):void   {
* }
*/

public class FMSPortTester
{
public static const FMS_URL:String = "127.0.0.1";
public static const PREFIX_1935:String = "rtmp://";
public static const PREFIX_80:String = "rtmpt://";

public static const SOCKET_TIMEOUT:Number = 3;

public function FMSPortTester() {   trace("static only class"); }

public static function TestPorts(_resultURLCallBack:Function):void  {
// Create socket connection to fms to check the ports
var socketTest:Socket = new Socket();
socketTest.connect(FMS_URL, 1935);
socketTest.addEventListener(Event.CONNECT, onSocketConnected);
socketTest.addEventListener(IOErrorEvent.IO_ERROR, onSocketError);
socketTest.addEventListener(SecurityErrorEvent.SECURITY_ERROR,onSocketError);
socketTest.timeout = (SOCKET_TIMEOUT * 1000);

// is connected, fms ports ok
function onSocketConnected(_e:Event):void   {
_resultURLCallBack(PREFIX_1935 + "" + FMS_URL);
}

// on error, fms ports closed
function onSocketError(_e:*):void   {
_resultURLCallBack(PREFIX_80 + "" + FMS_URL);
}
}
}
}

Example of useing Custom Screen Manager in ActionScript 3

Written by . Filed under ActionScript 3. Tagged , , , , , , , , , , . .

Screen Manager.
When i write window based systems i always use a Screen Manager.
when i can control and manage and display object on my screen.

Every display object need to extends ScreenContent class, then
he can attached to the screen manager.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package {
import flash.display.Sprite;
// screen content Abstract

public class ScreenContentAbstract extends Sprite {

private var _contentContainer:Sprite;
public function ScreenContentAbstract():void
{

}

public function hideContent():void  {
// hide content
}

public function showContent():void  {
// show content
}

public function set content(_s:Sprite):void {   _contentContainer = s;      }
public function get content():Sprite        {   return _contentContainer;   }

}
}

Screen Manager class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;

public class ScreenManager extends Event
{
private var _contentContainer:Sprite;

public function ScreenManager(_f:Enforcer) {
_contentContainer = new Sprite();
}

// Add content to display
public function addContent(_content:ScreenContentAbstract):void {
_contentContainer.addChild(_content);
_content.addEventListener(MouseEvent.MOUSE_DOWN, contentMouseHandler);
}

// Remove content from display
public function removeContent(_content:ScreenContentAbstract):void  {
if (_contentContainer.contains(_content))
_contentContainer.removeChild(_content);
}

// Hide all content on display
public function hideAllContent():void   {
for (var i:int = 0; i &lt; _contentContainer.numChildren; i++) {
if (_contentContainer.getChildAt(i) is ScreenContentAbstract) {
(_contentContainer.getChildAt(i) as ScreenContentAbstract).hideContent();
}
}
}

// Show all content on display
public function hideAllContent():void   {
for (var i:int = 0; i &lt; _contentContainer.numChildren; i++) {
if (_contentContainer.getChildAt(i) is ScreenContentAbstract) {
(_contentContainer.getChildAt(i) as ScreenContentAbstract).showContent();
}
}
}

// Set focus on object on the display
public function setFocus(_content:ScreenContentAbstract):void   {
_contentContainer.setChildIndex(_content, _contentContainer.numChildren - 1);
}

// mouse handler for content
private function _contentMouseHandler(_e:MouseEvent):void   {
switch(_e.type) {
case MouseEvent.MOUSE_DOWN:
setFocus(_e.target as ScreenContentAbstract);
break;
}
}

// SINGLETON PATTERN
private static var instance:ScreenManager;
public static function getInstance():ScreenManager  {
if (instance == null)
instance = new ScreenManager(new Enforcer());
return instance;
}

}

}
class Enforcer{public function Enforcer()}

As you can see, you can add more functionality this is example only.

Thanks,
Garry Lachman