PHP Implementation of PNG Thumbnail Function Sharing for Generating Transparent Background
- 2021-07-07 06:47:36
- OfStack
Before, I wrote an PHP thumbnail generation function in WEB development notes. Although that function can generate thumbnails, it has a definite defect. When generating PNG thumbnails, the background is black. Today, I wrote another function to make up for it. The code is simple, that is, imagealphablending ($thumb, false); With imagesavealpha ($thumb, true); It is very important. The main thing is to save the alpha value of PNG, and don't lose it.
The function is as follows:
<?PHP
/*
*$sourePic: Original path
* $smallFileName: Small picture name
* $width: Small picture width
* $heigh: Small figure height
* Reproduced note www.chhua.com*/
function pngthumb($sourePic,$smallFileName,$width,$heigh){
$image=imagecreatefrompng($sourePic);//PNG
imagesavealpha($image,true);// It's important here It means don't lose it $sourePic Transparent color of image ;
$BigWidth=imagesx($image);// Large graph width
$BigHeigh=imagesy($image);// Height of large map
$thumb = imagecreatetruecolor($width,$heigh);
imagealphablending($thumb,false);// It's important here , It means not to merge colors , Direct use $img Image color replacement , Includes transparent colors ;
imagesavealpha($thumb,true);// It's important here , It means don't lose it $thumb Transparent color of image ;
if(imagecopyresampled($thumb,$image,0,0,0,0,$width,$heigh,$BigWidth,$BigHeigh)){
imagepng($thumb,$smallFileName);}
return $smallFileName;// Returns the path of the small picture Reproduced note www.chhua.com
}
pngthumb("a.png", "c.png", 300, 300);// Call
?>