Change image color to transparent using GD library
Change image color to transparent using GD library. The base color and the offset are the incoming parameters.
function color2transparent($filepath, $colorToConvert=255, $offset=20, $overwrite=0){
if(!is_file($_SERVER["
return("File not found, please check filepath!!");
}
$fileInfo = pathinfo($filepath);
$oldfile = $_SERVER["DOCUMENT_ROOT"] . $filepath;
$newfile = $_SERVER["DOCUMENT_ROOT"] . $fileInfo[dirname] . "/transp_
if(!is_file($newfile) || $overwrite){
$im = imagecreatefromjpeg($oldfile);
imagetruecolortopalette($im, true, 256);
$total = imagecolorstotal( $im );
for ( $i = 0; $i < $total; $i++ ) {
$index = imagecolorsforindex( $im, $i );
$red = ($index["red"] >= ($colorToConvert-$offset) || $index["red"] >= ($colorToConvert+$offset))?$
$green = ($index["green"]>= ($colorToConvert-$offset) || $index["green"] >= ($colorToConvert+$offset))?$
$blue = ($index["blue"] >= ($colorToConvert-$offset) || $index["blue"] >= ($colorToConvert+$offset))?$
imagecolorset( $im, $i, $red, $green, $blue );
}
$size = getimagesize($oldfile);
$img = imagecreatetruecolor($size[0],
$trans = imagecolorallocate($img, 255, 255, 255);
imagecolortransparent($img,$
imagecopy($img,$im,0,0,0,0,$
imagetruecolortopalette($img, true, 256);
imageinterlace($img);
imagepng($img,$newfile);
imagedestroy($img);
}
return($fileInfo[dirname] . "/" . basename($newfile));
}