12 years ago
If your building an AIR application and you want to have your own native custom file type association for your app, it is surprisingly easy to to with ActionScript 3 in air as I found out. I was unable to find any information on reading and writing custom files so I decided to post my experience here. I remembered watching a tutorial by Lee Brimelow at gotoAndLearn a while back where he showed how to decode a BMP file using ByteArrays. So I revised the tutorial and used the ideas from this to create my own file.
For this example I will create a simple graphic file containing some metadata and some bitmap data.
1. Write out the specification
The first thing you should do is map out a spec sheet for it, outlining all the data and datatypes you want to store and the order it will be written. This is important so you don’t forget later on, and if you want others to be able to use it as well. Your custom file must be read and written in the same order. I just did it in Notepad like so:
image name – String
image author – String
image width – int
image height – int
bitmapdata length – int
bitmapdata – bytearray
Note that this is a very basic file, so you could save all different data types such as Boolean, Number, String, int, uint etc.
2. Get your data into a ByteArray
To write the file first we need to create a bytearray and then using the write methods of the ByteArray class write the bits of data to it:
[cc lang=”actionscript”]
// the stuff we want to save – name, author and a bitmap – in this case I’ve created a red square 300x300px
var name:String = “a new picture”;
var author:String = “Ted Mosby”;
var bitmap:Bitmap = new Bitmap(new BitmapData(300,300,false,0xFF0000));
// convert bitmap to byte array
var bitmapBA:ByteArray = bitmap.bitmapData.getPixels();
// create a bytearray to save into file
var bytearray:ByteArray = new ByteArray();
// write the image name
bytearray.writeUTF(name);
// write author
bytearray.writeUTF(author);
// write image width and height
bytearray.writeInt(bitmap.width);
bytearray.writeInt(bitmap.height);
// write bitmap data length
bytearray.writeInt(bitmapBA.length);
// write the bitmap
bytearray.writeBytes(bitmapBA);
[/cc]
READ MORE