PHP Colorize an image using GD


Hits: 3184  

I was working for color customization for HTML5 MP3 Player with Playlist

Finally, I have time saving code for you PHP Colorize an image using GD

<?php

//print_r(html2rgb("#ffffff"));
//echo rgb2html(137, 113, 79); 

$color=isset($_REQUEST['color'])?$_REQUEST['color']:"ff00ff";
$image=isset($_REQUEST['image'])?$_REQUEST['image']:"2.jpg";

$rgb= html2rgb("#".$color);

$imgname=$image;
         
    $im=imagecreatefromjpeg($imgname);
    if($im&& imagefilter($im, IMG_FILTER_COLORIZE,$rgb[0],$rgb[1],$rgb[2]))
    {
         
         header("Content-Type: image/jpeg");
         imagejpeg($im);
         
         //imagejpeg($im, 'output.jpg'); 
         //imagedestroy($im); 
    }
   else
   {
        echo'Processing failed.';
   }
   

function rgb2html($r,$g=-1,$b=-1)
{
    if(is_array($r)&&sizeof($r)==3)
        list($r,$g,$b)=$r;

    $r=intval($r);$g=intval($g);
    $b=intval($b);

    $r=dechex($r<0?0:($r>255?255:$r));
    $g=dechex($g<0?0:($g>255?255:$g));
    $b=dechex($b<0?0:($b>255?255:$b));

    $color=(strlen($r)<2?'0':'').$r;
    $color.=(strlen($g)<2?'0':'').$g;
    $color.=(strlen($b)<2?'0':'').$b;
    return'#'.$color;
}

function html2rgb($color)
{
    if($color[0]=='#')
        $color=substr($color,1);

    if(strlen($color)==6)
        list($r,$g,$b)=array($color[0].$color[1],$color[2].$color[3],$color[4].$color[5]);
    elseif(strlen($color)==3)
        list($r,$g,$b)=array($color[0].$color[0],$color[1].$color[1],$color[2].$color[2]);
    else
        returnfalse;

    $r=hexdec($r);$g=hexdec($g);$b=hexdec($b);

    returnarray($r,$g,$b);
}

   
   
?>

The above code will work for JPG image files, you can optimize for other image formats 😉

=>

Published by

Sandeep Verma

I’m an Entrepreneur. I’m proud to work as Blogger, LAMP Programmer, Linux Admin, Web Consultant, Cloud Manager, Apps Developer, Searcher. Concentrate > Observe > Imagine > Launch