Skip to content

Instantly share code, notes, and snippets.

@vhdm
Created September 6, 2015 22:39
Show Gist options
  • Save vhdm/fdb66196d0592a6e0322 to your computer and use it in GitHub Desktop.
Save vhdm/fdb66196d0592a6e0322 to your computer and use it in GitHub Desktop.
Image to text (ASCII Image)
<!doctype html>
<html>
<head>
<title>ASCII Image</title>
</head>
<body>
<?php
function ascii_image($image) {
$result = '';
if(file_exists($_GET['image'])) {
if(substr($image, strrpos($image, '.')) == '.jpg') {
$img = imagecreatefromjpeg($image);
$result .= '<style type="text/css">'.PHP_EOL;
$result .= '.ascii_image {'.PHP_EOL;
$result .= 'font-family: Tahoma;'.PHP_EOL;
$result .= 'font-size: 1px;'.PHP_EOL;
$result .= 'line-height: 1px;'.PHP_EOL;
$result .= '}'.PHP_EOL;
$result .= '</style>'.PHP_EOL;
$iw = imagesx($img);
$ih = imagesy($img);
$result .= '<div class="ascii_image">'.PHP_EOL;
for($h = 0; $h < $ih; $h++) {
for($w = 0; $w < $iw; $w++) {
$rgb = imagecolorat($img, $w, $h);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = ($rgb >> 0) & 0xFF;
$result .= '<span style="color: rgb('.$r.','.$g.','.$b.');">#</span>';
}
$result .= ''.PHP_EOL;
}
$result .= '</div>'.PHP_EOL;
}
else {
$result .= 'Wrong File Type';
}
}
return $result;
}
// How to use it ?
if(isset($_GET['image'])) {
echo ascii_image($_GET['image']);
}
?>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment