SSJX.CO.UK
Browser Games | Cybiko | Amiga | Applications | Windows Games | Python | Guides | Site Map

Javascript RLE Compression

Run Length Compression (RLE) is an easy way to compress data that has large amounts of the same item. It works by storing the piece of data and the number of times it is to be repeated. e.g:

If we wanted to store: AAAAABBBBCCCDDE we would end up with:
5,A, 4,B, 3,C, 2,D, 1,E,

The downside of RLE compression is that if there are a lot of different items, and/or not many large groupings, the 'compressed' data can easily end up being bigger than it was to begin with!

Uses of RLE compression

RLE compression is very useful for embedding game maps in html5/canvas games. The advantages include:

Creating the compressed data

For my games I needed a program that could convert a 256 colour bitmap (.bmp) into RLE compressed array data, so I created this:

Download Bmp2rle (13k Zip)

Note! that this program is only useful for 256 colour (8bit) bitmaps, it will just output rubbish if it is fed any other kind of file!

Example

The example below shows how a 8x8 box (64 items) can be stored as 40 items.

var datain=[
8,1,
1,1,6,0,1,1
1,1,6,0,1,1
1,1,6,0,1,1
1,1,6,0,1,1
1,1,6,0,1,1
1,1,6,0,1,1
8,1
];

var dataout=new Array(8*8);

function rle_dec()
{
	var pos=0,i,x;
	
	for(i=0;i<datain.length;i+=2)
	{
		for(x=0;x<datain[i];x++)
		{
			dataout[pos++]=datain[i+1];
		}
	}
	
	console.log("In "+datain.length.toString() );
	console.log("Out "+pos.toString() );
}

Finally

Below is the output of a graphical version of the above code, the full source to it can be found here:

This requires a browser that supports HTML5 / Canvas

09/01/2013

Support this site : Visit Play-Asia for games and accessories for new and classic games consoles!