<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Jozef Chúťka&#039;s blog &#187; ByteArray</title>
	<atom:link href="http://blog.yoz.sk/tag/bytearray/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.yoz.sk</link>
	<description>My life, my work</description>
	<lastBuildDate>Tue, 31 Jan 2012 12:40:53 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Quick Tip: Compression in Flash</title>
		<link>http://blog.yoz.sk/2011/01/quick-tip-compression-in-flash/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=quick-tip-compression-in-flash</link>
		<comments>http://blog.yoz.sk/2011/01/quick-tip-compression-in-flash/#comments</comments>
		<pubDate>Fri, 07 Jan 2011 13:11:40 +0000</pubDate>
		<dc:creator>Jozef Chúťka</dc:creator>
				<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[AIR]]></category>
		<category><![CDATA[Flash / Flex]]></category>
		<category><![CDATA[ByteArray]]></category>
		<category><![CDATA[compress]]></category>
		<category><![CDATA[gzip]]></category>
		<category><![CDATA[gzuncompress]]></category>
		<category><![CDATA[lzma]]></category>
		<category><![CDATA[zip]]></category>

		<guid isPermaLink="false">http://blog.yoz.sk/?p=1993</guid>
		<description><![CDATA[While working on one of my projects where I needed compression for transfered data, I hit some very interesting compression libraries. Also the ByteArray class contains compress method, using zlib algorithm in flash player or multiple algorithms in AIR. At the end I decided to use ByteArray.compress() method for encoding vs. PHP gzuncompress for decoding, [...]]]></description>
			<content:encoded><![CDATA[<p>While working on one of my projects where I needed compression for transfered data, I hit some very interesting compression libraries. Also the <a href="http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/utils/ByteArray.html">ByteArray</a> class contains <a href="http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/utils/ByteArray.html#compress()">compress method</a>, using zlib algorithm in flash player or <a href="http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/utils/CompressionAlgorithm.html">multiple algorithms</a> in AIR. At the end I decided to use <a href="http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/utils/ByteArray.html#compress()">ByteArray.compress()</a> method for encoding vs. <a href="http://php.net/manual/en/function.gzuncompress.php">PHP gzuncompress</a> for decoding, what works correctly, fast and smooth.</p>
<p>Here is a list of 3rd party compression libraries and other good stuff:</p>
<ul>
<li><a href="http://nochump.com/blog/archives/15">AS3 Zip</a>: ActionScript 3 based library for reading and writing zip files</li>
<li><a href="http://codeazur.com.br/lab/fzip/">FZip</a>: FZip is an Actionscript 3 class library to load, modify and create standard ZIP archives.</li>
<li><a href="http://code.google.com/p/aszip/">ASZip</a>: ActionScript 3 library to generate ZIP files</li>
<li><a href="http://code.google.com/p/in-spirit/wiki/LZMAEncoder">LZMA Encoder</a>: AS3 class to compress data using LZMA algorithm.</li>
<li><a href="http://code.google.com/p/apparat/source/browse/#hg%2Fapparat-lzma-decoder%2Fsrc%2Fmain%2Fas3%2Fapparat%2Flzma">LZMA Decoder</a>: A part of the apparat framework.</li>
<li><a href="http://probertson.com/projects/gzipencoder/">GZIP</a>: ActionScript GZIP compression library</li>
<li><a href="http://blog.skinkers.com/2010/09/02/adding-gzip-support-for-flexair-httpservice-urlloader/">Gzip for HTTPService/URLLoader</a>: Adding Gzip support for Flex/AIR HTTPService/URLLoader</li>
<li><a href="http://code.google.com/p/airxzip/">airxzip</a>: Zip library for ActionScript3 on AIR</li>
</ul>
<p>If you know some more, please let me know.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.yoz.sk/2011/01/quick-tip-compression-in-flash/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Processing BitmapData.getPixels() With PHP</title>
		<link>http://blog.yoz.sk/2010/10/processing-bitmapdata-getpixels-with-php/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=processing-bitmapdata-getpixels-with-php</link>
		<comments>http://blog.yoz.sk/2010/10/processing-bitmapdata-getpixels-with-php/#comments</comments>
		<pubDate>Mon, 25 Oct 2010 11:35:41 +0000</pubDate>
		<dc:creator>Jozef Chúťka</dc:creator>
				<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[Flash / Flex]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[BitmapData]]></category>
		<category><![CDATA[ByteArray]]></category>
		<category><![CDATA[compress]]></category>
		<category><![CDATA[imagecolorallocate]]></category>
		<category><![CDATA[imagesetpixel]]></category>
		<category><![CDATA[unpack]]></category>

		<guid isPermaLink="false">http://blog.yoz.sk/?p=2547</guid>
		<description><![CDATA[Have you ever worked with BitmapData.getPixels() method? This method generates a byte array from a rectangular region of pixel data. Writes an unsigned integer (a 32-bit unmultiplied pixel value) for each pixel into the byte array. Thats sounds good, but what is it good for to have a ByteArray full of integers? There is not [...]]]></description>
			<content:encoded><![CDATA[<p>Have you ever worked with <a href="http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/BitmapData.html#getPixels()">BitmapData.getPixels()</a> method? This method <em>generates a byte array from a rectangular region of pixel data. Writes an unsigned integer (a 32-bit unmultiplied pixel value) for each pixel into the byte array</em>. Thats sounds good, but what is it good for to have a ByteArray full of integers? There is not even a decoder for this format on my backend?!&#8230; Well, this format is so cool, and easy to access that you do are able to write your own decoder e.g. in PHP.</p>
<p>The resulting bytes are 32-bit unsigned integers for each pixel represented by AARRGGBB format, followed by another pixels and so on e.g.:</p>
<pre class="brush: plain; title: ; notranslate">AA RR GG BB:
-- -- -- --
FF FF 00 00
00 00 FF 00</pre>
<p><span id="more-2547"></span></p>
<p>First pixel is full opaque red color, second pixel is full transparent green color. That sounds good enough to use with <a href="http://php.net/manual/en/function.imagesetpixel.php">imagesetpixel()</a>, that requires color in <a href="http://www.php.net/manual/en/function.imagecolorallocate.php">almost identic format</a>, however PHP GD library recognizes alpha values from 0 to 127 in reversed logic (127 full transparent, 0 full opaque). So we only need to change the alpha value and we are good to go:</p>
<pre class="brush: plain; title: ; notranslate">AA -&gt; AA (php)
--    --
FF -&gt; 00
00 -&gt; 7F</pre>
<p>What are we going to do is:</p>
<ul>
<li>this format does not know about width and height of image, we have to define it manualy</li>
<li>access pixels (unsigned integers) from byte array (<a href="http://cz.php.net/manual/en/function.unpack.php">unpack()</a> is the fastest method for this in PHP i guess)</li>
<li>iterate over each pixel / color</li>
<li>get color value and transform to PHP alpha logic
<ul>
<li><strong>$color>>24</strong> returns alpha value (0-255), what we need is to divide it by two (0-127 for php) so <strong>$color&gt;&gt;25</strong> works fine</li>
<li>inversed logic requires values to be changed from 0-127 to 127-0: <strong>0x7f-AA</strong></li>
<li>shift alpha value back to its correct position <strong>AA&lt;&lt;24</strong></li>
<li>add original RRGGBB values to our new alpha <strong>AA|($color&amp;0xffffff)</strong></li>
</ul>
</li>
<li>pass transformed color value into imagesetpixel() with correct x, y coordinate</li>
</ul>
<p>This process should return correct image identifier. Lets have a new PHP function imagecreatefrombmdstring()</p>
<pre class="brush: php; title: ; notranslate">&lt;?php
function imagecreatefrombmdstring($bytes, $width, $height)
{
	$img=imagecreatetruecolor($width, $height);
	imagealphablending($img, false);
	imagesavealpha($img, true);

	$x=0;
	$y=0;
	$colors=unpack(&quot;N*&quot;, $bytes);
	foreach($colors as $color)
	{
		imagesetpixel($img, $x, $y, (0x7f-($color&gt;&gt;25)&lt;&lt;24)|($color&amp;0xffffff));
		if(++$x==$width)
		{
			$x=0;
			$y++;
		}
	}
	return $img;
}</pre>
<p>The ActionScript code may look something like this, this method is in fact very fast on client side:</p>
<pre class="brush: as3; title: ; notranslate">var bitmapData:BitmapData = ...
var bytes:Bytes=bitmapData.getPixels(bitmapData.rect);
var loader:URLLoader = new URLLoader();
var request:URLRequest = new URLRequest();
request.url = &quot;our.php&quot;;
request.contentType = &quot;application/octet-stream&quot;;
request.method = URLRequestMethod.POST;
request.data = bytes;
loader.load(request);</pre>
<p>To optimize it even more, use <a href="http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/utils/ByteArray.html#compress()">ByteArray.compress()</a> to compress bytes before sending, now you should get binary request not much bigger than length of the same request containing <a href="http://blog.yoz.sk/2010/06/quick-tip-fastest-actionscript-pngencoder/">PNG encoded</a> image bytes. On PHP side use <a href="http://php.net/manual/en/function.gzuncompress.php">gzuncompress()</a> to get raw bytes.</p>
<p>Why did I developer/used this method of sending image to server? Well, I was not able to find fast enought/asynchronous PNG encoder. By using this technique, I was able to scale the getPixels+compress process into multiple frames (asynchronously) in order to create smooth upload process (using <a href="http://code.google.com/p/in-spirit/wiki/MultipartURLLoader">MultipartURLLoader</a>).</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.yoz.sk/2010/10/processing-bitmapdata-getpixels-with-php/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Pixel Bender Inputs &#8211; Vector or ByteArray</title>
		<link>http://blog.yoz.sk/2010/08/pixel-bender-inputs-vector-or-bytearray/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=pixel-bender-inputs-vector-or-bytearray</link>
		<comments>http://blog.yoz.sk/2010/08/pixel-bender-inputs-vector-or-bytearray/#comments</comments>
		<pubDate>Mon, 02 Aug 2010 13:07:13 +0000</pubDate>
		<dc:creator>Jozef Chúťka</dc:creator>
				<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[Flash / Flex]]></category>
		<category><![CDATA[ByteArray]]></category>
		<category><![CDATA[Endian]]></category>
		<category><![CDATA[pixel bender]]></category>
		<category><![CDATA[Shader]]></category>
		<category><![CDATA[ShaderJob]]></category>
		<category><![CDATA[Vector]]></category>

		<guid isPermaLink="false">http://blog.yoz.sk/?p=2105</guid>
		<description><![CDATA[Pixel Bender for Flash Player lets you play some more advanced games. Based on your needs you can force your kernels to &#8220;eat&#8221; not only BitmapData, but also ByteArray-s or Vector-s. With this knowledge, you can simply use Pixel Bender kernels for some fast math or processing like 3D engines (3D to 2D projection) etc. [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://blog.yoz.sk/wp-content/uploads/pixelbender.png" alt="" title="pixelbender" width="200" height="100" class="alignleft size-full wp-image-2130" /></p>
<p><a href="http://www.adobe.com/devnet/pixelbender/">Pixel Bender</a> for Flash Player lets you play some more advanced games. Based on your needs you can force your kernels to &#8220;eat&#8221; not only BitmapData, but also ByteArray-s or Vector-s. With this knowledge, you can simply use Pixel Bender kernels for some fast math or processing like 3D engines (3D to 2D projection) etc. Lets have a look at some simple demos, how to push vector and raw bytes directly into shader via ShaderJob:</p>
<p><span id="more-2105"></span></p>
<h3>Vector.&lt;Number&gt;</h3>
<p>Simple (one-dimension) vector may be recognized by pixel bender as 3-channel input just as simple as providing correct width/height for shader:</p>
<pre class="brush: as3; title: ; notranslate">var src:Vector.&lt;Number&gt; = new Vector.&lt;Number&gt;();
while(someLooping)
{
    src.push(x);
    src.push(y);
    src.push(z);
}

var shader:Shader = new Shader(code);
shader.data.src.input = src;
shader.data.src.width = src.length / 3; // forces pixel bender to use image3 as input
shader.data.src.height = 1;

var res:Vector.&lt;Number&gt; = new Vector.&lt;Number&gt;();
var job:ShaderJob = new ShaderJob(shader, res, src.length / 3, 1);
job.start(true);

for(var i:uint=0; i&lt;src.length; i+=3)
{
    x = res[i];
    y = res[i+1];
    z = res[i+2];
}</pre>
<h3>ByteArray</h3>
<p>If you are more in &#8220;low-level&#8221; things, try using raw bytes as input. Do not forget to setup LITTLE_ENDIAN for source and result variables. Also make sure width*height*4 results in source bytes length.</p>
<pre class="brush: as3; title: ; notranslate">var src:ByteArray = new ByteArray();
src.endian = Endian.LITTLE_ENDIAN;
src.position = 0;
while(someLooping)
{
    src.writeFloat(x);
    src.writeFloat(y);
    src.writeFloat(z);
}

var shader:Shader = new Shader(code);
shader.data.src.input = src;
shader.data.src.width = 256; // e.g.
shader.data.src.height = src.length/4/256;

var res:ByteArray = new ByteArray();
res.endian = Endian.LITTLE_ENDIAN;

var job:ShaderJob = new ShaderJob(shader, res, 256, src.length/4/256);
job.start(true);

res.position = 0;
for(var i:uint = 0; i&lt;src.length/4; i++)
{
    x = res.readFloat();
    y = res.readFloat();
    z = res.readFloat();
}</pre>
<p>Lets have a look at how pixel bender handles input and outputs. As with current version of pixel bender/flash player it seems like:</p>
<pre class="brush: plain; title: ; notranslate">'res' : cannot have 1 or 2 channel outputs</pre>
<p>&#8230; but you can use 3 or 4 channel outputs (float3, pixel3).</p>
<pre class="brush: xml; title: ; notranslate">&lt;languageVersion : 1.0;&gt;
kernel threed &lt;namespace : &quot;sk.yoz&quot;;vendor : &quot;Yoz&quot;;version : 1;&gt;
{
    input image3 src;
    output float3 res; // or pixel3
    void evaluatePixel()
    {
        res = sample(src, outCoord());
        // we have res.x, res.y and res.z
    }
}</pre>
<p>Where to go from here:</p>
<ul>
<li><a href="http://www.flashmagazine.com/tutorials/detail/using_pixel_bender_to_calculate_information/">Using Pixel Bender to calculate information</a></li>
<li><a href="http://www.huesforalice.com/project/47">Number crunching with as3 and pixelbender</a></li>
<li><a href="http://www.adobe.com/devnet/flex/articles/flashbuilder4_pixelbender.html">Using Pixel Bender with Flash Builder 4 as a number crunching engine</a></li>
<li><a href="http://www.unitzeroone.com/blog/2009/03/18/flash-10-massive-amounts-of-3d-particles-with-alchemy-source-included/">Flash 10, Massive amounts of 3D particles with Alchemy (source included).</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.yoz.sk/2010/08/pixel-bender-inputs-vector-or-bytearray/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Inline Images</title>
		<link>http://blog.yoz.sk/2010/02/inline-images/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=inline-images</link>
		<comments>http://blog.yoz.sk/2010/02/inline-images/#comments</comments>
		<pubDate>Tue, 16 Feb 2010 14:59:44 +0000</pubDate>
		<dc:creator>Jozef Chúťka</dc:creator>
				<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[Flash / Flex]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[base64]]></category>
		<category><![CDATA[Bitmap]]></category>
		<category><![CDATA[ByteArray]]></category>
		<category><![CDATA[ExternalInterface]]></category>
		<category><![CDATA[PNGEncoder]]></category>

		<guid isPermaLink="false">http://blog.yoz.sk/?p=1106</guid>
		<description><![CDATA[Have you ever heard about inline images? Inline images use the data URI scheme to embed images directly within web pages. As defined by RFC 2397, data URIs are designed to embed small data items as &#8220;immediate&#8221; data, as if they were referenced externally. This basicaly means, you can insert base64 encoded byte code of [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://blog.yoz.sk/wp-content/uploads/inlineImage-200x122.png" alt="" title="inlineImage" width="200" height="122" class="alignleft size-medium wp-image-1111" /></p>
<p>Have you ever heard about <a href="http://www.websiteoptimization.com/speed/tweak/inline-images/">inline images</a>? Inline images use the data URI scheme to embed images directly within web pages. As defined by RFC 2397, data URIs are designed to embed small data items as &#8220;immediate&#8221; data, as if they were referenced externally. This basicaly means, you can insert base64 encoded byte code of any image directly into html file. Using inline images saves HTTP requests over externally referenced objects. Data URIs can potentially <a href="http://www.greywyvern.com/code/php/binary2base64">store any type of data</a>, not just images!</p>
<p><span id="more-1106"></span></p>
<p>This example creates snapshot of flash application (on left side) and dynamicly (using javascript) creates inline image (right side) with base64 encoded bytes in src attribute. (right side is html &lt;img&gt;)</p>
<p><iframe width="100%" height="300" style="border:none;" src="http://blog.yoz.sk/examples/inlineImages/"></iframe></p>
<p>Application source:</p>
<pre class="brush: xml; title: ; notranslate">&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;mx:Application xmlns:mx=&quot;http://www.adobe.com/2006/mxml&quot; layout=&quot;vertical&quot;
    enterFrame=&quot;enterFrame()&quot; borderStyle=&quot;solid&quot; borderColor=&quot;#000000&quot;
    backgroundColor=&quot;#ffffff&quot;&gt;
&lt;mx:Script&gt;
&lt;![CDATA[
    import com.adobe.images.PNGEncoder;
    import com.dynamicflash.util.Base64;

    private function enterFrame():void
    {
        if(!container || !container.width)
            return;

        container.graphics.beginFill(Math.random() * 0xffffff, Math.random());
        container.graphics.drawCircle(
            Math.random() * container.width,
            Math.random() * container.height, Math.random() * 30);

    }

    private function makeSnapshot(source:DisplayObject):void
    {
        var script:String = 'var img = document.getElementById(&quot;img&quot;);'
            + 'if(!img)'
            + '{'
                + 'img = document.createElement(&quot;IMG&quot;);'
                + 'img.id=&quot;img&quot;;'
                + 'document.body.appendChild(img);'
            + '}'
            + 'img.src=&quot;' + getSrc(source) +'&quot;;';
        ExternalInterface.call(&quot;function(){&quot; + script + &quot;}&quot;);
    }

    private function getByteArray(source:DisplayObject):ByteArray
    {
        var bitmapData:BitmapData = new BitmapData(source.width, source.height);
        bitmapData.draw(source);
        var bitmap:Bitmap = new Bitmap(bitmapData);
        return PNGEncoder.encode(bitmapData);
    }

    private function getSrc(source:DisplayObject):String
    {
        var byteArray:ByteArray = getByteArray(source);
        return 'data:image/png;base64,'
            + Base64.encodeByteArray(byteArray);
    }
]]&gt;
&lt;/mx:Script&gt;
&lt;mx:Container id=&quot;container&quot; width=&quot;100%&quot; height=&quot;100%&quot;/&gt;
&lt;mx:Button label=&quot;Make Snapshot&quot; click=&quot;makeSnapshot(this)&quot;/&gt;
&lt;/mx:Application&gt;</pre>
<p>Data URLs save HTTP requests. When combined with CSS sprites, data URLs can save numerous HTTP requests. It would be interesting to see if data URLs can be combined with USEMAPS or make a data URL CSS sprite. Data URLs are a convenient way to create self-enclosed web pages that don&#8217;t rely on external objects to render.</p>
<ul>
<li>Save HTTP requests, avoids adding to object overhead</li>
<li>Save concurrent thread &#8211; browsers default to two simultaneous connections per hostname</li>
<li>HTTPS requests are simplified and performance improved</li>
</ul>
<p>Well, for now I have no idea how can flash benefit from data urls <img src='http://blog.yoz.sk/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />  but if I come to something I let you know.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.yoz.sk/2010/02/inline-images/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Compressing hex string into base64 string</title>
		<link>http://blog.yoz.sk/2009/11/compressing-hex-string-into-base64-string/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=compressing-hex-string-into-base64-string</link>
		<comments>http://blog.yoz.sk/2009/11/compressing-hex-string-into-base64-string/#comments</comments>
		<pubDate>Mon, 30 Nov 2009 12:16:00 +0000</pubDate>
		<dc:creator>Jozef Chúťka</dc:creator>
				<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[Flash / Flex]]></category>
		<category><![CDATA[base64]]></category>
		<category><![CDATA[ByteArray]]></category>
		<category><![CDATA[compress]]></category>
		<category><![CDATA[convert]]></category>
		<category><![CDATA[hex]]></category>
		<category><![CDATA[p16Top64]]></category>
		<category><![CDATA[p64Top16]]></category>
		<category><![CDATA[readUnsignedInt]]></category>
		<category><![CDATA[writeUnsignedInt]]></category>

		<guid isPermaLink="false">http://blog.yoz.sk/?p=718</guid>
		<description><![CDATA[How would you convert / compress 64 character long hex string (0-9a-f) into shortest possible web-safe-char string? (base64 chars is fine) The reverse algorithm must be able to &#8220;uncompress&#8221; resulting string back into original hex. I have created p16Top64() compress algorithm and p64Top16() uncompress (reversed) algorithm based on ByteArray class and writeUnsignedInt(), readUnsignedInt() methods. Both [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.yoz.sk/wp-content/uploads/compressLooseWeight1.jpg"><img src="http://blog.yoz.sk/wp-content/uploads/compressLooseWeight1-200x120.jpg" alt="compressLooseWeight" title="compressLooseWeight" width="200" height="120" class="alignleft size-medium wp-image-733" /></a></p>
<p>How would you convert / compress 64 character long hex string (0-9a-f) into shortest possible web-safe-char string? (base64 chars is fine) The reverse algorithm must be able to &#8220;uncompress&#8221; resulting string back into original hex.</p>
<p>I have created p16Top64() compress algorithm and p64Top16() uncompress (reversed) algorithm based on ByteArray class and writeUnsignedInt(), readUnsignedInt() methods. Both p16Top64() and p64Top16() methods are now part of <a href="http://classes.yoz.sk/sk/yoz/data/Serialization.as">sk.yoz.data.Serialization</a> class. By using p16Top64() method I was able to compress original 64 chars into 44 chars. But, is it possible to compress it into less than 44 char long base64 (0-9a-Z/=) string?</p>
<p><span id="more-718"></span></p>
<p>To be more specific lets assume your original string is:</p>
<pre class="brush: plain; title: ; notranslate">295eb2c90b37696bb9256d05e404ad037078092214ce73cbe838302a04818507</pre>
<p>My compress and uncompress methods:</p>
<pre class="brush: as3; title: ; notranslate">import com.dynamicflash.util.Base64; // !use this Base64 class!

public static function p16Top64(p16:String):String
{
    var b:ByteArray = new ByteArray();
    var s:String = p16;
    while(s.length)
    {
        b.writeUnsignedInt(parseInt(&quot;0x&quot; + s.substr(0, 8), 16));
        s = s.substr(8);
    }
    b.position = 0;
    return Base64.encodeByteArray(b);
}

public static function p64Top16(p64:String):String
{
    var r:String = &quot;&quot;;
    var b:ByteArray = Base64.decodeToByteArray(p64);
    var x:String = &quot;&quot;;
    b.position = 0;
    while(b.position &lt; b.length)
    {
        x = b.readUnsignedInt().toString(16);
        r += String(&quot;00000000&quot;).substr(x.length) + x;
    }
    return r;
}</pre>
<p>Lets test it:</p>
<pre class="brush: as3; title: ; notranslate">Serialization.p16Top64(&quot;295eb2c90b37696bb9256d05e404ad037078092214ce73cbe838302a04818507&quot;)
// returns 64 chars.: KV6yyQs3aWu5JW0F5AStA3B4CSIUznPL6DgwKgSBhQc=</pre>
<p>This is more less first time I have used ByteArray this way, so maybe there is even a better usage. If you can think of one, just let me know.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.yoz.sk/2009/11/compressing-hex-string-into-base64-string/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Bitmap, BitmapData, ByteArray&#8230;</title>
		<link>http://blog.yoz.sk/2009/10/bitmap-bitmapdata-bytearray/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=bitmap-bitmapdata-bytearray</link>
		<comments>http://blog.yoz.sk/2009/10/bitmap-bitmapdata-bytearray/#comments</comments>
		<pubDate>Thu, 15 Oct 2009 12:26:40 +0000</pubDate>
		<dc:creator>Jozef Chúťka</dc:creator>
				<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[Flash / Flex]]></category>
		<category><![CDATA[Bitmap]]></category>
		<category><![CDATA[BitmapData]]></category>
		<category><![CDATA[ByteArray]]></category>
		<category><![CDATA[converting]]></category>
		<category><![CDATA[DisplayObject]]></category>
		<category><![CDATA[encoding]]></category>
		<category><![CDATA[image]]></category>
		<category><![CDATA[Loader]]></category>
		<category><![CDATA[LoaderInfo]]></category>
		<category><![CDATA[url]]></category>
		<category><![CDATA[URLRequest]]></category>

		<guid isPermaLink="false">http://blog.yoz.sk/?p=135</guid>
		<description><![CDATA[Lets see how to convert between Bitmap, BitmapData and ByteArray in few examples: DisplayObject to BitmapData BitmapData to Bitmap BitmapData to ByteArray URL (image) to ByteArray (asynchronous) URL (image) to BitmapData (asynchronous) ByteArray to BitmapData (asynchronous) DisplayObject to BitmapData. FYI DisplayObject is any visible object in flash (Sprite, MovieClip, Bitmap, UIComponent, Video etc&#8230;): BitmapData to [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.yoz.sk/wp-content/uploads/bitmap_converting.png"><img src="http://blog.yoz.sk/wp-content/uploads/bitmap_converting-200x119.png" alt="bitmap_converting" title="bitmap_converting" width="200" height="119" class="alignleft size-medium wp-image-452" /></a></p>
<p>Lets see how to convert between Bitmap, BitmapData and ByteArray in few examples:</p>
<ul style="float:left;">
<li>DisplayObject to BitmapData</li>
<li>BitmapData to Bitmap</li>
<li>BitmapData to ByteArray</li>
<li>URL (image) to ByteArray (asynchronous)</li>
<li>URL (image) to BitmapData  (asynchronous) </li>
<li>ByteArray to BitmapData  (asynchronous) </li>
</ul>
<div style="clear:both;"></div>
<p><span id="more-135"></span></p>
<p>DisplayObject to BitmapData. FYI <a href="http://livedocs.adobe.com/flex/3/langref/flash/display/DisplayObject.html">DisplayObject is any visible object in flash</a> (Sprite, MovieClip, Bitmap, UIComponent, Video etc&#8230;):</p>
<pre class="brush: as3; title: ; notranslate">import flash.display.BitmapData;
var bitmapData:BitmapData = new BitmapData(button.width, button.height, false, 0xFFFFFF);
bitmapData.draw(button);
// result: bitmapData</pre>
<p>BitmapData to Bitmap:</p>
<pre class="brush: as3; title: ; notranslate">import flash.display.Bitmap;
var bitmap:Bitmap = new Bitmap(bitmapData);
// result: bitmap</pre>
<p>BitmapData to ByteArray. Requires jpeg / png or any other encoder. <a href="http://blog.yoz.sk/2009/10/actionscript-3-encoding-jpeg/">Read more about JPEG encoding here</a>:</p>
<pre class="brush: as3; title: ; notranslate">import mx.graphics.codec.JPEGEncoder;
import flash.utils.ByteArray;
var encoder:JPEGEncoder = new JPEGEncoder(90);
var byteArray:ByteArray = encoder.encode(bitmapData));
// result: byteArray</pre>
<p>URL (image) to ByteArray. Asynchronous operation:</p>
<pre class="brush: as3; title: ; notranslate">import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.events.Event;
import flash.net.URLRequest;
import flash.utils.ByteArray;

var loader:Loader = new Loader();
loader.load(new URLRequest(&quot;banner1.jpg&quot;));
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaderComplete);

private function loaderComplete(event:Event):void
{
    var loaderInfo:LoaderInfo = LoaderInfo(event.target);
    var byteArray:ByteArray = loaderInfo.bytes;
    // result: byteArray
}</pre>
<p>URL (image) to BitmapData. Asynchronous operation:</p>
<pre class="brush: as3; title: ; notranslate">import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.events.Event;
import flash.net.URLRequest;
import flash.display.BitmapData;

var loader:Loader = new Loader();
loader.load(new URLRequest(&quot;banner1.jpg&quot;));
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaderComplete);

private function loaderComplete(event:Event):void
{
    var loaderInfo:LoaderInfo = LoaderInfo(event.target);
    var bitmapData:BitmapData = new BitmapData(loaderInfo.width, loaderInfo.height, false, 0xFFFFFF);
    bitmapData.draw(loaderInfo.loader);
    // result: bitmapData
}</pre>
<p>ByteArray to BitmapData. Asynchronous operation:</p>
<pre class="brush: as3; title: ; notranslate">import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.events.Event;
import flash.display.BitmapData;

var loader:Loader = new Loader();
loader.loadBytes(byteArray);
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaderComplete);

private function loaderComplete(event:Event):void
{
    var loaderInfo:LoaderInfo = LoaderInfo(event.target);
    var bitmapData:BitmapData = new BitmapData(loaderInfo.width, loaderInfo.height, false, 0xFFFFFF);
    bitmapData.draw(loaderInfo.loader);
    // result: bitmapData
}</pre>
<p><a href="http://www.bytearray.org/?p=1089">Synchronous JPEG ByteArray to BitmapData can be found here</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.yoz.sk/2009/10/bitmap-bitmapdata-bytearray/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Serialization</title>
		<link>http://blog.yoz.sk/2009/10/serialization/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=serialization</link>
		<comments>http://blog.yoz.sk/2009/10/serialization/#comments</comments>
		<pubDate>Tue, 13 Oct 2009 07:59:11 +0000</pubDate>
		<dc:creator>Jozef Chúťka</dc:creator>
				<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[Flash / Flex]]></category>
		<category><![CDATA[ByteArray]]></category>
		<category><![CDATA[serialization]]></category>
		<category><![CDATA[String]]></category>

		<guid isPermaLink="false">http://blog.yoz.sk/?p=264</guid>
		<description><![CDATA[This classes let you serialize your ActionScript 3 Objects to ByteArray or String: sk.yoz.data.Serialization com.dynamicflash.util.Base64 sk.yoz.data.Serialization containst public static classes only, that lets you convert between objects, bytearrays and strings: com.dynamicflash.util.Base64 is class from Steve Webster, and I use it in Serialization while Base64Encoder and Base64Decoder did not worked for me (flex sdk 3.4): Usage:]]></description>
			<content:encoded><![CDATA[<p>This classes let you serialize your ActionScript 3 Objects to ByteArray or String:</p>
<ul>
<li><a href="http://classes.yoz.sk/sk/yoz/data/Serialization.as">sk.yoz.data.Serialization</a></li>
<li><a href="http://classes.yoz.sk/com/dynamicflash/util/Base64.as">com.dynamicflash.util.Base64</a></li>
</ul>
<p><span id="more-264"></span></p>
<p><a href="http://classes.yoz.sk/sk/yoz/data/Serialization.as">sk.yoz.data.Serialization</a> containst public static classes only, that lets you convert between objects, bytearrays and strings:</p>
<pre class="brush: as3; title: ; notranslate">package sk.yoz.data
{
    import flash.utils.ByteArray;
    import com.dynamicflash.util.Base64;

    public class Serialization
    {
        public static function objectToString(data:Object):String
        {
            var bytes:ByteArray = objectToBytes(data);
            return bytesToString(bytes);
        }

        public static function stringToObject(data:String):Object
        {
            var bytes:ByteArray = stringToBytes(data);
            return bytesToObject(bytes);
        }

        public static function objectToBytes(data:Object):ByteArray
        {
            var bytes:ByteArray = new ByteArray();
            bytes.writeObject(data);
            bytes.position = 0;
            return bytes;
        }

        public static function bytesToString(bytes:ByteArray):String
        {
            return Base64.encodeByteArray(bytes);
        }

        public static function stringToBytes(data:String):ByteArray
        {
            return Base64.decodeToByteArray(data);
        }

        public static function bytesToObject(bytes:ByteArray):Object
        {
            bytes.position = 0;
            return bytes.readObject();
        }
    }
}</pre>
<p><a href="http://classes.yoz.sk/com/dynamicflash/util/Base64.as">com.dynamicflash.util.Base64</a> is class from <a href="http://dynamicflash.com/goodies/base64/">Steve Webster</a>, and I use it in Serialization while Base64Encoder and Base64Decoder did not worked for me (flex sdk 3.4):</p>
<pre class="brush: as3; title: ; notranslate">/*
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 &quot;Software&quot;), 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 &quot;AS IS&quot;, 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 com.dynamicflash.util {

	import flash.utils.ByteArray;

	public class Base64 {

		private static const BASE64_CHARS:String = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=&quot;;

		public static const version:String = &quot;1.1.0&quot;;

		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 = &quot;&quot;;

			// 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 &gt; 0) {
				// Create new data buffer and populate next 3 bytes from data
				dataBuffer = new Array();
				for (var i:uint = 0; i &lt; 3 &amp;&amp; data.bytesAvailable &gt; 0; i++) {
					dataBuffer[i] = data.readUnsignedByte();
				}

				// Convert to data buffer Base64 character positions and
				// store in output buffer
				outputBuffer[0] = (dataBuffer[0] &amp; 0xfc) &gt;&gt; 2;
				outputBuffer[1] = ((dataBuffer[0] &amp; 0x03) &lt;&lt; 4) | ((dataBuffer[1]) &gt;&gt; 4);
				outputBuffer[2] = ((dataBuffer[1] &amp; 0x0f) &lt;&lt; 2) | ((dataBuffer[2]) &gt;&gt; 6);
				outputBuffer[3] = dataBuffer[2] &amp; 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 &lt; 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 &lt; 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 &lt; 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 &lt; 4 &amp;&amp; i + j &lt; data.length; j++) {
					dataBuffer[j] = BASE64_CHARS.indexOf(data.charAt(i + j));
				}

      			// Decode data buffer back into bytes
				outputBuffer[0] = (dataBuffer[0] &lt;&lt; 2) + ((dataBuffer[1] &amp; 0x30) &gt;&gt; 4);
				outputBuffer[1] = ((dataBuffer[1] &amp; 0x0f) &lt;&lt; 4) + ((dataBuffer[2] &amp; 0x3c) &gt;&gt; 2);
				outputBuffer[2] = ((dataBuffer[2] &amp; 0x03) &lt;&lt; 6) + dataBuffer[3];

				// Add all non-padded bytes in output buffer to decoded data
				for (var k:uint = 0; k &lt; 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(&quot;Base64 class is static container only&quot;);
		}
	}
}</pre>
<p>Usage:</p>
<pre class="brush: as3; title: ; notranslate">var s:Object = {hallo:&quot;hallo&quot;};
var r:Object = Serialization.stringToObject(Serialization.objectToString(s));
trace(r); // equals to s</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.yoz.sk/2009/10/serialization/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>ActionScript 3 encoding JPEG, alchemy</title>
		<link>http://blog.yoz.sk/2009/10/actionscript-3-encoding-jpeg/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=actionscript-3-encoding-jpeg</link>
		<comments>http://blog.yoz.sk/2009/10/actionscript-3-encoding-jpeg/#comments</comments>
		<pubDate>Fri, 09 Oct 2009 11:53:05 +0000</pubDate>
		<dc:creator>Jozef Chúťka</dc:creator>
				<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[Flash / Flex]]></category>
		<category><![CDATA[alchemy]]></category>
		<category><![CDATA[asynchronous]]></category>
		<category><![CDATA[Bitmap]]></category>
		<category><![CDATA[BitmapData]]></category>
		<category><![CDATA[ByteArray]]></category>
		<category><![CDATA[converting]]></category>
		<category><![CDATA[encoding]]></category>
		<category><![CDATA[image]]></category>
		<category><![CDATA[jpeg]]></category>
		<category><![CDATA[JPEGEncoder]]></category>

		<guid isPermaLink="false">http://blog.yoz.sk/?p=136</guid>
		<description><![CDATA[Lets assume you want to save an image (or any DisplayObject) from flash to disk, or upload to facebook etc. What you need is to encode your BitmapData into an Jpeg and send ByteArray raw data to be saved/uploaded. There are few ways how to do it. First, you can use original adobe mx.graphics.codec.JPEGEncoder. Sadly, [...]]]></description>
			<content:encoded><![CDATA[<p>Lets assume you want to save an image (or any DisplayObject) from flash to disk, or upload to facebook etc. What you need is to encode your BitmapData into an Jpeg and send ByteArray raw data to be saved/uploaded. There are few ways how to do it.</p>
<p>First, you can use original adobe mx.graphics.codec.JPEGEncoder. Sadly, this encoder is the slowest. There were attemps to make it faster by otpimizing code by <a href="http://www.bytearray.org/">bytearray.org</a>, that resulted into two times faster <a href='http://classes.yoz.sk/org/bytearray/images/JPEGEncoder.as'>org.bytearray.images.JPEGEncoder</a>. Usage is pretty simple:</p>
<p><span id="more-136"></span></p>
<pre class="brush: as3; title: ; notranslate">import org.bytearray.JPEGEncoder;

function encode():ByteArray
{
    var bitmapData:BitmapData = new BitmapData(this.width, this.height, false);
    bitmapData.draw(this);
    var encoder:JPEGEncoder = new JPEGEncoder(80);
    return encoder.encode(bitmapData);
}</pre>
<p>But not fast enough <img src='http://blog.yoz.sk/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> . Since Flash Player 10 introduced <a href="http://labs.adobe.com/technologies/alchemy/">alchemy</a> (compiled C and C++ code within flash apps), it was possible to use <a href='http://classes.yoz.sk/jpegencoder.swc'>optimized C++ encoder to do the work</a>. Encoding time is more than 30 times faster than the original JPEGEncoder, pretty cool huh? Code looks like this</p>
<pre class="brush: as3; title: ; notranslate">import cmodule.jpegencoder.CLibInit;

function encode():ByteArray
{
    var bitmapData:BitmapData = new BitmapData(this.width, this.height, false);
    bitmapData.draw(this);
    var init:CLibInit = new CLibInit();
    var lib:Object = init.init();
    var byteArray:ByteArray = new ByteArray();
    var byteArrayOut:ByteArray = new ByteArray();
    byteArray = bitmapData.getPixels(bitmapData.rect);
    byteArray.position = 0;
    lib.encode(byteArray, byteArrayOut, bitmapData.width, bitmapData.height, 80);
    return byteArrayOut;
}</pre>
<p>You can also run your encoding in asynchronous mode&#8230; Read more and see tests here:</p>
<ul>
<li><a href="http://segfaultlabs.com/blog/post/asynchronous-jpeg-encoding">Alchemy &#8211; asynchronous jpeg encoding</a></li>
<li><a href="http://www.websector.de/blog/2009/06/21/speed-up-jpeg-encoding-using-alchemy/">Speed up JPEG encoding using Alchemy</a></li>
<li><a href="http://labs.adobe.com/technologies/alchemy/">Alchemy technology</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.yoz.sk/2009/10/actionscript-3-encoding-jpeg/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>

