Az Expattech az ünnepek alatt (dec.24-jan.1.) zárva tart. Nyitás: 2024.január 2

ExpatTech Techblog

Peter Todd 2010.10.01. 10:49

Flash Cookbook - Tricks - Store data in bytearray and compress it

You can create a nice little drawing application using the flash graphics tools. Let's say you created an application, where you press the mousebutton, start to draw and draw lines by holding the button down. Every point your mouse reached is stored in an array at an ENTER_FRAME event.

This way I did a hand-drawn rectangle, consisting 36 points. If you want to save this drawing point by point, you save this array in the SharedObjects or send it to a server-side script to save it somewhere on the server.

Now, in my example, the set is made of 36 points. If I turn it into a string

points.toString();

then it becomes a 575 character long string. This string is then saved to the server and everybody is happy.

Wait a minute. Let's draw something more complex. 199 points becomes 3183 characters long, 496 becomes 7935 characters.

Now we could do some tricky apporximations to make the set smaller. But wait! I don't want an apporximation! But what to do then?

Here comes the ByteArray into the picture. If we write our array into the ByteArray, we get these values:

# of points length of string length of bytes
26 415 292
36 575 386
199 3183 2071
496 7935 5249

Nice. We decreased the length of our storageplace. But is there a better way to do this? Yes, there is. ByteArray class has a method called compress. "Flash Player supports only the default algorithm, zlib" - says the documenation (doc), but this will be fine for now. Maybe if the guys expand it, we can try different methods, but for now this will be perfect.

Let's see the result table if we include the results of the compression

# of points length of string length of bytes length of compressed bytes
26 415 292 114
36 575 386 143
199 3183 2071 734
496 7935 5249 1879

Yes, if you compare the raw string to the compressed byte method, you get an average of 4 time compression (compressed size is 25% of the original size). Note that now we kept all the points as they are, no approxamition, no nothing.

Basic code for doing the things above:

var bytes:ByteArray = new ByteArray();
bytes.writeObject(points);
bytes.compress();

And so:

bytes.uncompress();
var points:Array = bytes.readObject();

to uncompress it.

We will talk about how to store the compresses bytearray in another post.