Image to Text

So I've always wanted to make a script that read an image, and spat out ASCII art of that image. A few semesters back I wrote one, and I figured I'd share it here.
#!/usr/bin/perl -w

use strict;
use GD;

## Open the image, and get its size
my $src = GD::Image->newFromPng('src.png', 1)
	or die('Failed to open image: '.$!);
my ($swidth, $sheight) = $src->getBounds();

## Print out the html header
open OUT, '>out.html';
print OUT qq#<!doctype><html><head><title>ASCII Art</title>
	<style type="text/css">
		body{
			font-size:25%;
			letter-spacing:0px;
			line-height:80%;
			background-color:white;
		}
		div{
			display:inline;
			/*width:1px;
			height:1px;*/
		}
	</style></head><body><p>\n#;

## Loop through all the pixels: left to right, top to bottom
for(my $y = 0; $y < $sheight; $y++) {
	for(my $x = 0; $x < $swidth; $x++) {
		
		## Get the RGB info for a given pixel
		my ($r, $g, $b)	= $src->rgb($src->getPixel($x, $y));
		
		## Convert the values to Hexidecimal
		my ($hr, $hg, $hb);
		$hr = sprintf("%x",$r);
		$hg = sprintf("%x",$g);
		$hb = sprintf("%x",$b);
		
		## Add proceeding zeros where applicable
		s/^([0-9a-f])$/0$1/ foreach(($hr, $hg, $hb));
		
		## Compile the hex string
		my $hex = $hr.$hg.$hb;
		
		## Print the "Pixel" to the html page
		print OUT "<span style=\"color:#$hex\">x</span>";
	}
	print OUT "<br />";
}

## Make sure to close all the tags
print OUT "</p></body></html>";
close OUT;
I might even wrap an IRC bot around this somehow. Or create a module, or something. Donno yet.

Tags: