Convertire una immagine in Ascii Art con PHP!

Posted on 03. Nov, 2009 by daniele in php, tutorials


Questa funzione PHP converte una immagine in Ascii Art. Le librerie GD si occupano di fare il lavoro più noioso, cioè quello dispostare alcuni bit per creare le sfumature delle immagini.

 
< ?php
 
function image2ascii( $image )
{
    // return value
    $ret = '';
 
    // open the image
    $img = ImageCreateFromJpeg($image); 
 
    // get width and height
    $width = imagesx($img);
    $height = imagesy($img); 
 
    // loop for height
    for($h=0;$h<$height;$h++)
    {
        // loop for height
        for($w=0;$w<=$width;$w++)
        {
            // add color
            $rgb = ImageColorAt($img, $w, $h);
            $r = ($rgb >> 16) & 0xFF;
            $g = ($rgb >> <img src='http://www.sastgroup.com/wp-includes/images/smilies/icon_cool.gif' alt='8)' class='wp-smiley' /> & 0xFF;
            $b = $rgb & 0xFF;
            // create a hex value from the rgb
            $hex = '#'.str_pad(dechex($r), 2, '0', STR_PAD_LEFT).str_pad(dechex($g), 2, '0', STR_PAD_LEFT).str_pad(dechex($b), 2, '0', STR_PAD_LEFT);
 
            // now add to the return string and we are done
            if($w == $width)
            {
                $ret .= '';
            }
            else
            {
                $ret .= '<span style="color:'.$hex.';">#</span>';
            }
        }
    }
    return $ret;
}
 
//ESEMPIO APPLICATO
 
// an image to convert
$image = 'test.jpg';
 
// do the conversion
$ascii = image2ascii( $image );
 
// and show the world
echo $ascii; 
 
?>
 

Correlati

Leave a reply