#!/bin/env perl
use warnings;
use strict;
use GD;

my $imagefile = shift;
my $outputfile = shift;
$outputfile = $imagefile . '.html' unless $outputfile;

my $type = `file -i $imagefile`;
$type =~ /.*: (.*\/.*)$/;
$type = $1;

open(IMAGEFILE, $imagefile) or die('Could not open file');
my $image;
if($type eq "image/jpeg") {
  print STDERR "Loading image of type " . $type . "\n";
  $image = newFromJpeg GD::Image(IMAGEFILE) or die('Could not load image from JPEG-file');
} elsif($type eq "image/png") {
  print STDERR "Loading image of type " . $type . "\n";
  $image = newFromPng GD::Image(IMAGEFILE) or die('Could not load image from PNG-file');
} else {
  die('Could not recognize file of type ' . $type);
}
close(IMAGEFILE);

print STDERR "Opening file " . $outputfile . " for output.\n";
open(HTMLFILE, ">$outputfile");
print HTMLFILE '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n";
print HTMLFILE '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">' . "\n";
print HTMLFILE "<head>\n";
print HTMLFILE '<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />' . "\n";
print HTMLFILE '<style type="text/css">' . "\n";
print HTMLFILE "  body { background-color: black; }\n";
print HTMLFILE "  div.image { font-family: verdana; font-size: 6px; }\n";
print HTMLFILE "</style>\n";
print HTMLFILE "</head>\n";
print HTMLFILE "<body>\n";
print HTMLFILE '<div class="image">' . "\n";
my($xSize, $ySize) = $image->getBounds();

my($R, $G, $B) = (-1);

my @text = split(//, "img2html");
@text = (@text, @text) while ($xSize * $ySize > scalar(@text));

my $r;
for($r = 0; $r < $ySize; $r += 2) {
  my $c;
   for($c = 0; $c < $xSize; $c++) {
     my $pixel = $image->getPixel($c, $r);
     my($r, $g, $b) = $image->rgb($pixel);
     my $color = '#' . sprintf("%.2X%.2X%.2X", $r, $g, $b);
     my $bin = int(rand 2);
     print HTMLFILE '<font color="' . $color .'">' . $bin . '</font>';
   }
   print HTMLFILE "<br />\n";
}
print HTMLFILE "</div>\n</body>\n</html>";

close(HTMLFILE);

