[8] Saving images created using BitmapData

This is something that I was thinking about a while ago and when someone asked how to do it on the forum I thought I better give it a shot, and this is what I came up with.

It requires PHP to make it work, and remember to update the location of the PHP Script if you’re trying this out (line 20).

import flash.display.BitmapData;

//*****************************************************************
// DRAWING THE BITMAP - click on black to draw green and vice-versa.
var color:Number = 0;
var drawing:Boolean = false;
var bitmap:BitmapData = new BitmapData(10, 10, false);

bitmap.fillRect(bitmap.rectangle, 0); _root.attachBitmap(bitmap, 0); _root._x += 10; _root._y += 10;
_root.onMouseDown = function() { if (_xmouse < bitmap.width && _ymouse < bitmap.height && _xmouse >= 0 && _ymouse >= 0) { color = bitmap.getPixel(_xmouse, _ymouse)==0?0x00FF00:0; drawing = true; } }
_root.onMouseMove = function() { if (_xmouse < bitmap.width && _ymouse < bitmap.height && _ymouse >= 0) { bitmap.setPixel(_xmouse, _ymouse, color); } }
_root.onMouseUp = function() { drawing = false; }

//*****************************************************************
// PREPARING AND SENDING THE INFORMATION TO A PHP PAGE - press enter
_root.onEnterFrame = function() { if (Key.isDown(Key.ENTER)) { sendBitmap(bitmapToString(_root.bitmap)); } }
function sendBitmap(bm:String) { 
	var output:MovieClip = _root.createEmptyMovieClip("output", _root.getNextHighestDepth());
	output.bitmap = bm;
	output.getURL("http://localhost/bitmap/", "_blank", "GET");
	output.removeMovieClip();
}
function bitmapToString(bm:BitmapData) {
	var output:String = bm.width+"a"+bm.height;
	for(y=0; y<bm.height; y++) {
		for (x=0; x<bm.width; x++) {
			output = output + "a" + bm.getPixel(x, y);
		}
	}
	return output;
}
<?

	$bitmapString = isset($_GET['bitmap'])?$_GET['bitmap']:"";
	$bitmapArray = explode("a", $bitmapString);
	$width = array_shift($bitmapArray);
	$height = array_shift($bitmapArray);
	header("Content-type: image/jpeg");
	$im = &imagecreatetruecolor($width, $height);
	foreach ($bitmapArray as $key=>$value) { imagesetpixel($im, $key%$width, floor($key/$width), $value); }
	imagejpeg($im);
	imagedestroy($im);

?>

Enjoy :thumb:
And if anyone has any suggestions or improvements please post about them :slight_smile: