通过PHP实现PNG转JPG

来源:互联网 发布:考研英语单词书 知乎 编辑:程序博客网 时间:2024/06/11 18:41

最近因为项目需要,将网页保存的png转换为jpg,于是结合网上的例子,更改成自己想要的函数。

函数直接在php中调用即可,输入参数为png文件全路径,保存为名字相同的jpg文件,可以选择是否删除原jpg文件。

代码如下:

//png2jpgfunction 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);        imagecolorallocate($dstImage, 255, 255, 255);        //读取图片        $srcImage = ImageCreateFromPNG($srcFile);        //合拼图片        imagecopyresampled($dstImage, $srcImage, 0, 0, 0, 0, $pw, $ph, $pw, $ph);        imagejpeg($dstImage, $dstFile, 90);        if ($delOri)        {            unlink($srcFile);        }        imagedestroy($srcImage);    }}


0 0
原创粉丝点击