Montag, 21. April 2014

PHP: IMG to coloured (HTML) ASCII

This little script takes an image file (on the server!) and computes a coloured ASCII (better: HTML) image out of it.

Use it like this, on a computer with php: imagescript.php?file=myfile.jpg

Have fun.
<DOCTYPE html>
<html>
<head>
<title>ASCII IMAGE</title>
<style>

body
{
color: #FFF;
background-color: #000;
line-height: 0.8;
}

</style>
</head>
<body>

<center>
<kbd>
<nobr>

<?php
// get the filename
$filename=$_GET['file'];
// get some image values
list($width, $height, $imgtype) = getimagesize($filename);

// select filetype and create image
switch($imgtype)
{
case IMAGETYPE_JPEG: $im=imagecreatefromjpeg($filename);break;
case IMAGETYPE_PNG: $im=imagecreatefrompng($filename);break;
        // add other file types as you like it.
default: $im=-1;
}

if($im!=-1)
{
// compute the for-step. Only x is needed.
$stepx=1;
        $stepy=1;

// if($height>100) {$stepy=$height/100;} // [obsolete]
if($width>100) {$stepx=$width/100;}
$stepy=$stepx; // [new]

// go through the image
for($y=0;$y<$height;$y+=$stepy)
{
for($x=0;$x<$width;$x+=$stepx)
{
// compute the color
$rgb=imagecolorat($im,$x,$y);
                        // get the hex values
$r=dechex(red($rgb));

$g=dechex(green($rgb));
$b=dechex(blue($rgb));
                        // add zeros if needed.
if(strlen($r)==1) {$r="0$r";}
if(strlen($g)==1) {$g="0$g";}
if(strlen($b)==1) {$b="0$b";}
                        // html color.   
$col="$r$g$b";
// print out a character
echo("<font color=\"#$col\">#</font>");
}
// print out a line end.
echo("<br>\n");
}
}else{
echo("File type not recognized. Sorry.");
}

// some helper functions to get color values
function red($rgb)
{
 return ($rgb >> 16) & 0xFF;
}
function green($rgb)
{
 return ($rgb >> 8) & 0xFF;
}
function blue($rgb)
{
 return $rgb & 0xFF;
}
?>

</nobr>
</kbd>
</center>
</body>

</html>

Keine Kommentare:

Kommentar veröffentlichen