Feeling Lucky?

Yesterday, I saw several posts on good ol’ Twitter pointing out this¬†Frederick McSwain portrait of Tobias Wong created in dice. While not meaning to detract from the personal sentiments and hard work of this intriguing piece of art, I just thought that using dice would be an interesting way to create some ascii images.

So, I found this free dice font and sat down and created the simple class below.

/**
 *	Copyright (c) 2011 Devon O. Wolfgang
 *
 *	Permission is hereby granted, free of charge, to any person obtaining a copy
 *	of this software and associated documentation files (the "Software"), 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 "AS IS", 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.onebyonedesign.extras {
 
	import flash.display.BitmapData;
	import flash.geom.Matrix;
	import flash.text.TextFormat;
 
	/**
	 * Convert image to a string of dice
	 * @author Devon O.
	 */
	public class AsciiDice {
 
		// very nice dice font found here: http://www.ambor.com/public/dice/dice.html
		[Embed(source = "assets/fonts/dice.ttf", fontFamily = "dice", mimeType = "application/x-font", unicodeRange="U+0031-U+0036", embedAsCFF = "false")]
		private static const DICE_FONT:Class;
 
		private static const FONT_SIZE:int = 12;
 
		private static const DIVSOR:Number = 0xFF / 6;
 
		public static const DICE_FORMAT:TextFormat = new TextFormat(new DICE_FONT().fontName, FONT_SIZE, 0x000000);
 
		/**
		 * @private
		 */
		public function AsciiDice(){
			// use static renderImage() method and TEXT_FORMAT
		}
 
		/**
		 * Call this static method to get back an ascii String
		 * @param	image		BitmapData of image to convert to Dice Ascii
		 * @param	maxWidth	Largest width of converted image
		 * @param	maxHeight	Largest height of converted image
		 * @return	String of ascii text
		 */
		public static function renderImage(image:BitmapData, maxWidth:int = 800, maxHeight:int = 800):String {
			// make a copy of the image
			var newImage:BitmapData;
			var scale:Matrix;
			// first resize image to fit given bounds
			if (image.width > maxWidth || image.height > maxHeight) {
				scale = new Matrix();
				var ratio:Number;
 
				// if portrait
				if (image.height > image.width) {
					ratio = maxHeight / image.height;
					scale.scale(ratio, ratio);
					newImage = new BitmapData(image.width * ratio, maxHeight, false, 0x000000);
					newImage.draw(image, scale);
 
				// if landscape
				} else {
					ratio = maxWidth / image.width;
					scale.scale(ratio, ratio);
					newImage = new BitmapData(maxWidth, image.height * ratio, false, 0x000000);
					newImage.draw(image, scale);
				}
			}
 
 
			if (!newImage) newImage = image.clone();
 
			// now scale by fontsize
			var imgWidth:int = newImage.width / FONT_SIZE;
			var imgHeight:int = newImage.height / FONT_SIZE;
			scale = new Matrix();
			scale.scale(1 / FONT_SIZE, 1 / FONT_SIZE);
			var imgData:BitmapData = new BitmapData(imgWidth, imgHeight, false, 0x000000);
			imgData.draw(newImage, scale);
			var pixels:Vector.<uint> = imgData.getVector(imgData.rect);
			newImage.dispose();
 
			// create string
			var i:int = 0;
			var j:int = 0;
			var len:int = pixels.length;
			var imgString:String = "";
 
			while (i < len) {
				for (j = 0; j < imgWidth; j++) {
					var avg:uint = getPixelAverage(pixels[i]);
					var v:Number = (avg / DIVSOR);
					v = v == 0 ? 1 : v;
					v = 7 - (v == int(v) ? v : int(v + 1));
 
					imgString += String(v);
 
					i++;
				}
				imgString += "\n";
			}
			imgData.dispose();
 
			return imgString;
		}
 
		private static function getPixelAverage(pix:uint):uint {
			var r:uint  = pix >> 16 & 0xFF;
			var g:uint  = pix >> 8 & 0xFF;
			var b:uint  = pix & 0xFF;
			return (r + g + b) / 3;
		}
	}
}

To use it (which you’re free to do), you’ll need the font mentioned above in a directory named ‘fonts’ within a directory named ‘assets’ in the same directory as the AsciiDice.as class file (com.onebyonedesign.extras). Create a TextField instance and set its defaultTextFormat property to AsciiDice.DICE_FORMAT. Also be sure to let it autosize and set its embedFonts and multiline properties to true.

Finally, just use the static renderImage() method to set the text property of your textfield (passing it the bitmapdata of the image you’d like to render as dice and a maximum width and height if you’d like).

Here’s a quick example (incidentally, if you choose to upload an image, I set the maximum filesize to 500k and I didn’t bother with error messages. So if you try to upload something and nothing happens, try using an image with a smaller filesize).

Get Adobe Flash player

Leave a Reply

Devon O. Wolfgang

Technical Reviewer of “The Essential Guide to Flash CS4 AIR Development”

Contributing Author of “Flash AS3 for Interactive Agencies”

Senior Software Engineer at Meez

Starling Particle Editor

vignette

Some Photographic Shaders


A couple weeks ago I was contacted and asked to develop some filters for Starling that could be used in a mobile camera app[…]

boids

Animated Particles, Books, and Code – It’s a New Year


It’s a new year[…]

bug

Logical Or Assignment Bug in ASC2


So, here’s something to keep an eye on if switching to AIR 3.8[…]

Starling Filter Collection

Starling Filter Collection


Building up a collection of filters for the Starling framework[…]

Starling Warp

Warp Filter for Starling


Another filter for the Starling framework[…]

promise

Promises Promises


What it boils down to is handling asynchronous tasks […] in a clean, intelligent fashion […]

GodRays

Starling ‘God Ray’ Filter


While cruising the internet today looking for interesting things to try out I ran across this fun little GPU Gem[…]

Alpha in Starling Filters and Basic Branching in AGAL


In plain English to create a circular mask we would want to do something like this[…]

Starling, Nape Physics, and PhysicsEditor


A look at using the PhysicsEditor tool for Nape and Starling […]

Playing With a Couple Game Ideas


Just a couple game fragments, really[…]

One More Filter For Starling


Another filter for the Starling framework[…]

Filters in Starling


Using and writing filters in the Starling framework[…]

Towards a Better Scratch


Perhaps it was too much Meat Beat Manifesto in the late 80’s […]

Learning AGAL with AGALMacroAssembler and OpenGL Examples

So the other day I sat down and thought to myself: self, it’s high time you learn you some of this new fancy pants AGAL[…]

UV Scrolling in Starling


Obviously this could come in pretty darned handy for space games, side scrollers, etc, etc[…]

Drawing on Stuff in Away3D 4.0

So, Easter Day, I thought I’d sit down and make a little ‘Paint on an Egg and Send it to Your Friend’ app.