需求很简单,就是将png转化为白色背景的jpg,找了下,发现都是黑色背景的,查阅了国外的代码,发现少了两句,结合测试通过,整理如下:

function png2jpg($srcPathName, $delOri=true){
$srcFile=$srcPathName;
$srcFileExt=strtolower(trim(substr(strrchr($srcFile,'.'),1)));
if($srcFileExt=='png'){
$dstFile = str_replace('.png', '.jpg', $srcPathName);
$photoSize = GetImageSize($srcFile);
$pw = $photoSize[0];
$ph = $photoSize[1];
$dstImage = ImageCreateTrueColor($pw, $ph);
$white = imagecolorallocate($dstImage, 255, 255, 255);#背景色
$srcImage = ImageCreateFromPNG($srcFile);
imagefilledrectangle($dstImage, 0, 0, $pw, $ph, $white);
imagecopyresampled($dstImage, $srcImage, 0, 0, 0, 0, $pw, $ph, $pw, $ph);
imagejpeg($dstImage, $dstFile, 90);
if ($delOri){
unlink($srcFile);
}
imagedestroy($srcImage);
}
}

原始函数来自:http://blog.csdn.net/autumoonchina/article/details/46341295
白色背景解决办法来自:stackoverflow.com/questions/2569970/gd-converting-a-png-image-to-jpeg-and-making-the-alpha-by-default-white-and-not#answer-2570015

Related Posts: PHP-png转换jpg-白色背景函数示例 :