猿问

使用PHP通过压缩将PNG转换为JPG?

我有一堆高质量的PNG文件。我想使用PHP将它们转换为JPG,因为它的文件较小,同时又保持了质量。我想在网上显示JPG文件。

PHP是否具有执行此操作的功能/库?质量/压缩度好吗?


慕丝7291255
浏览 642回答 3
3回答

慕斯王

这样做可以将PNG安全地转换为白色透明的JPG。$image = imagecreatefrompng($filePath);$bg = imagecreatetruecolor(imagesx($image), imagesy($image));imagefill($bg, 0, 0, imagecolorallocate($bg, 255, 255, 255));imagealphablending($bg, TRUE);imagecopy($bg, $image, 0, 0, 0, 0, imagesx($image), imagesy($image));imagedestroy($image);$quality = 50; // 0 = worst / smaller file, 100 = better / bigger file imagejpeg($bg, $filePath . ".jpg", $quality);imagedestroy($bg);

慕少森

请注意您要转换的内容。JPG不支持Alpha透明度,而PNG则支持。您将丢失该信息。要进行转换,您可以使用以下功能:// Quality is a number between 0 (best compression) and 100 (best quality)function png2jpg($originalFile, $outputFile, $quality) {    $image = imagecreatefrompng($originalFile);    imagejpeg($image, $outputFile, $quality);    imagedestroy($image);}此函数使用GD库中的imagecreatefrompng()和imagejpeg()函数。

繁华开满天机

<?phpfunction createThumbnail($imageDirectory, $imageName, $thumbDirectory, $thumbWidth) {&nbsp; &nbsp; $explode = explode(".", $imageName);&nbsp; &nbsp; $filetype = $explode[1];&nbsp; &nbsp; if ($filetype == 'jpg') {&nbsp; &nbsp; &nbsp; &nbsp; $srcImg = imagecreatefromjpeg("$imageDirectory/$imageName");&nbsp; &nbsp; } else&nbsp; &nbsp; if ($filetype == 'jpeg') {&nbsp; &nbsp; &nbsp; &nbsp; $srcImg = imagecreatefromjpeg("$imageDirectory/$imageName");&nbsp; &nbsp; } else&nbsp; &nbsp; if ($filetype == 'png') {&nbsp; &nbsp; &nbsp; &nbsp; $srcImg = imagecreatefrompng("$imageDirectory/$imageName");&nbsp; &nbsp; } else&nbsp; &nbsp; if ($filetype == 'gif') {&nbsp; &nbsp; &nbsp; &nbsp; $srcImg = imagecreatefromgif("$imageDirectory/$imageName");&nbsp; &nbsp; }&nbsp; &nbsp; $origWidth = imagesx($srcImg);&nbsp; &nbsp; $origHeight = imagesy($srcImg);&nbsp; &nbsp; $ratio = $origWidth / $thumbWidth;&nbsp; &nbsp; $thumbHeight = $origHeight / $ratio;&nbsp; &nbsp; $thumbImg = imagecreatetruecolor($thumbWidth, $thumbHeight);&nbsp; &nbsp; imagecopyresized($thumbImg, $srcImg, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $origWidth, $origHeight);&nbsp; &nbsp; if ($filetype == 'jpg') {&nbsp; &nbsp; &nbsp; &nbsp; imagejpeg($thumbImg, "$thumbDirectory/$imageName");&nbsp; &nbsp; } else&nbsp; &nbsp; if ($filetype == 'jpeg') {&nbsp; &nbsp; &nbsp; &nbsp; imagejpeg($thumbImg, "$thumbDirectory/$imageName");&nbsp; &nbsp; } else&nbsp; &nbsp; if ($filetype == 'png') {&nbsp; &nbsp; &nbsp; &nbsp; imagepng($thumbImg, "$thumbDirectory/$imageName");&nbsp; &nbsp; } else&nbsp; &nbsp; if ($filetype == 'gif') {&nbsp; &nbsp; &nbsp; &nbsp; imagegif($thumbImg, "$thumbDirectory/$imageName");&nbsp; &nbsp; }}&nbsp; &nbsp; ?>这是一个非常好的缩略图脚本=)这是一个示例:$ path =原始图片所在文件夹的路径。$ name =要为其制作缩略图的文件的文件名。$ thumbpath =要将缩略图保存到的目录的路径。$ maxwidth = PX中缩略图的最大宽度,例如 100(将为100px)。createThumbnail($path, $name, $thumbpath, $maxwidth);
随时随地看视频慕课网APP
我要回答