Runtime Color to Transparent Image Conversion
This function converts a given color(parameter) to tranparent, creating a new image with 'transp_' prefix, all in runtime using PHP. Image runtime conversion from color to tranparent. Runtime conversion color to transparent PHP.
function color2transparent($filepath, $colorToConvert=255, $offset=20, $overwrite=0){
if(!is_file($_SERVER["DOCUMENT_ROOT"] . $filepath)){
return("File not found, please check filepath!!");
}
$fileInfo = pathinfo($filepath);
$oldfile = $_SERVER["DOCUMENT_ROOT"] . $filepath;
$newfile = $_SERVER["DOCUMENT_ROOT"] . $fileInfo[dirname] . "/transp_.png";
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))?$colorToConvert:$index["red"];
$green = ($index["green"]>= ($colorToConvert-$offset) || $index["green"] >= ($colorToConvert+$offset))?$colorToConvert:$index["green"];
$blue = ($index["blue"] >= ($colorToConvert-$offset) || $index["blue"] >= ($colorToConvert+$offset))?$colorToConvert:$index["blue"];
imagecolorset( $im, $i, $red, $green, $blue );
}
$size = getimagesize($oldfile);
$img = imagecreatetruecolor($size[0],$size[1]);
$trans = imagecolorallocate($img, 255, 255, 255);
imagecolortransparent($img,$trans);
imagecopy($img,$im,0,0,0,0,$size[0],$size[1]);
imagetruecolortopalette($img, true, 256);
imageinterlace($img);
imagepng($img,$newfile);
imagedestroy($img);
}
return($fileInfo[dirname] . "/" . basename($newfile));
}