code prettify

Sunday, 7 February 2016

How to generate text representation of an image using PHP?

We will learn how to convert an image to its text representation using PHP that can be used in an html page (if any such requirement arises in your application or just for fun sake :) ).

The steps followed to convert the image to text representation are:

1. Get the width and height of the image to be converted.
2. Loop through every pixel value in the image.
3. At every pixel value, find the color at that position.
4. Apply that color to a # symbol we use to represent that pixel.
5. Finally we get the text representation of the image represented by # (hashes).


    <body style="background-color: #000000;">

$img = imagecreatefromjpeg('red_leaf.jpg');
$dx = imagesx($img);
$dy = imagesy($img);

// Loop through each pixel in the image and check the color
// Then do something with that color data like display the # character
// at the appropriate color for each pixel.
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";



Image used in the program:

Sample output can be seen here.

Cool isn't it :)

No comments:

Post a Comment