back

Tink.pl

This was a little something I created to make coloured text html from an image. I'd seen this knocking around in various places on the web and fanced having a dabble at making my own. It's a simple piece of code, you get the rgb value for a pixel and then write a character taken from the textfile with the same rbg value as a piece of html. Then you repeat the process for the next pixel and next character in the textfile (looping round if the end of the textfile is reached). Simple.

Click here for an example html document (543kb) of an 144 x 185 pixel image of my friend Dave with fontsize of 6 and a lineheight of 4.

usage: perl tink.pl image textfile fontsize lineheight
(fontsize and linheight are both given in pixels, output will need to be redirected to a file)
#!/usr/bin/perl

use GD;

$imagefilename = $ARGV[0];
$textfilename = $ARGV[1];
$fontsize = $ARGV[2];
$linesize = $ARGV[3];

$imagedata = GD::Image->new($imagefilename);

if (! open (TEXTHANDLE, $textfilename) ) {
	print "no file - $!\n";
	exit(0);
}

@textdata = <TEXTHANDLE>;
close (TEXTHANDLE);

foreach $item (@textdata) {				# bodge it down into a single string
    $thetext = $thetext . $item;
    }

$thetext =~ s/\n//g;					# get rid of the newlines
$thetext =~ s/ //g;						# get rid of the spaces
$thetext =~ s/\>//g;
$thetext =~ s/\<//g;

$textsize = length $thetext;
($width , $height) = $imagedata->getBounds();

$letter = 0;

$or = 256;
$og = 256;
$ob = 256;

print q(<html><body bgcolor=#000000 style="font-size: ) . "$fontsize" . q(px; line-height: ) . "$linesize" . q(px; font-family: courier new;">);

for ( $y = 0 ; $y < $height ; $y++ ) {
	for ( $x = 0; $x < $width ; $x++ ) {
		( $r ,$g , $b ) = $imagedata->rgb( $imagedata->getPixel( $x , $y ) );
		
		if ( ($r == $or) && ($g = $og) && ($b == $ob) ) { $samecolour = 1; }
		
		$mr = sprintf ("%02x" , $r);
		$mg = sprintf ("%02x" , $g);
		$mb = sprintf ("%02x" , $b);
		
		if ( $samecolour != 1) { print q(</font><font color=#)."$mr"."$mg"."$mb".q(>); }
		
		$aletter = substr ( $thetext, $letter , 1);
		print "$aletter";
		$letter++;
		if ( $letter == $textsize ) { $letter = 0; }
				
		$or = $r;
		$og = $g;
		$ob = $b;
		$samecolour = 0;
	}
	print q(<br>);
}

print q(</font></body></html>);

All this code is © 2006 - 2015, except for the noted pieces which are © to their authors as noted. Feel free to use anything you find here, I'm not that precious about it. Take it, improve it, make lots of cash with it, it's a gift.

back