<?php


//read-only of width and height after frist GET
function sendGetPage () {
  
//too many ' and " in heredoc?
  
$serverNamePhpSelf = $_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'];

echo <<< endOfGetPage
<html>
<head>
<title>PHP Convert image file to ascii art</title>
</head>
<body bgcolor="black" text="white">
Specify a small image file to be converted to HTMLized-ASCII art
<br>
<form name="uploadForm"
enctype="multipart/form-data"
action="http://$serverNamePhpSelf";
method="post">
  Filename:
<input type="file" size="30" maxlength="100"  name="uploadFile">
<input value="Upload" type="submit">
</form>
endOfGetPage;
}

//initial page load.  display form
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
  
bail("");    //no error.
}


$uploadFileTmp_name = $_FILES['uploadFile']['tmp_name'];
$uploadFileName = $_FILES['uploadFile']['name'];
$uploadFileSize = $_FILES['uploadFile']['size'];

if (!
is_uploaded_file($uploadFileTmp_name) || $uploadFileSize==0) {
  
bail("<b>Bad file! </b>Try again<p>\n");
}  



//echo "uploadFileName: ".$uploadFileName."<br>\n";
//echo "uploadFileTmp_name: ".$uploadFileTmp_name."<br>\n";

$pathinfoArray = pathinfo($uploadFileName);
$extension = strtoupper($pathinfoArray['extension']);
//echo "file extension: ".$extension."<br>\n";

switch ($extension) {
case
'PNG':
   
$im = ImageCreateFromPNG($uploadFileTmp_name);
   break;
case
'GIF':
   
$im = ImageCreateFromGIF($uploadFileTmp_name);
   break;
case
'JPG':
case
'JPEG':
   
$im = ImageCreateFromJPEG($uploadFileTmp_name);
   break;
default:
   
bail("<b>Unknown file type: $extension</b><p>\n");
}

$dx = ImageSX($im);
$dy = ImageSY($im);
if (
$dx>300 || $dy>300) {
  
bail("<b>File too big!</b><p>\n");
}  

sendGetPage();

echo
"<pre>\n";
echo
"<font size=\"1\">\n";
//from "Programming PHP":
for($y=0; $y < $dy; $y++){
  for(
$x=0; $x < $dx; $x++){
    
$col = ImageColorAt($im, $x, $y);
    
$rgb = ImageColorsForIndex($im, $col);
    
printf('<font color=#%02x%02x%02x>#</font>',
       
$rgb['red'], $rgb['green'], $rgb['blue']);
  }
  
//  echo "<br>\n";
  
echo "\n";
}
echo
"</pre>\n";
ImageDestroy($im);


echo
"</body>\n</html>";




function
bail ($reason) {
  echo
$reason;
  
sendGetPage();
  echo
"</body>\n</html>";
  exit();
}

?>