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

Joh*_*ohn 49 php png jpeg

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

PHP有功能/库来做到这一点吗?质量/压缩是否有益?

Dan*_*eón 171

这样做可以将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);
Run Code Online (Sandbox Code Playgroud)

  • 这是将PNG安全地转换为JPG的最正确方法.想为此回复添加最高++评级. (8认同)

And*_*ore 58

小心你要转换的内容.当PNG这样做时,JPG不支持alpha透明度.你将失去这些信息.

要转换,您可以使用以下功能:

// 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);
}
Run Code Online (Sandbox Code Playgroud)

此函数使用GD库中imagecreatefrompng()imagejpeg()函数和函数.

  • 请查看danLeon安全地将PNG转换为JPG的答案. (11认同)
  • 此答案不适用于具有透明度的png文件. (4认同)

Al.*_*Al. 11

这是一个小例子,将'image.png'转换为'image.jpg',图像质量为70%:

<?php
$image = imagecreatefrompng('image.png');
imagejpeg($image, 'image.jpg', 70);
imagedestroy($image);
?>
Run Code Online (Sandbox Code Playgroud)

希望有所帮助


小智 10

<?php
function createThumbnail($imageDirectory, $imageName, $thumbDirectory, $thumbWidth) {
    $explode = explode(".", $imageName);
    $filetype = $explode[1];

    if ($filetype == 'jpg') {
        $srcImg = imagecreatefromjpeg("$imageDirectory/$imageName");
    } else
    if ($filetype == 'jpeg') {
        $srcImg = imagecreatefromjpeg("$imageDirectory/$imageName");
    } else
    if ($filetype == 'png') {
        $srcImg = imagecreatefrompng("$imageDirectory/$imageName");
    } else
    if ($filetype == 'gif') {
        $srcImg = imagecreatefromgif("$imageDirectory/$imageName");
    }

    $origWidth = imagesx($srcImg);
    $origHeight = imagesy($srcImg);

    $ratio = $origWidth / $thumbWidth;
    $thumbHeight = $origHeight / $ratio;

    $thumbImg = imagecreatetruecolor($thumbWidth, $thumbHeight);
    imagecopyresized($thumbImg, $srcImg, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $origWidth, $origHeight);

    if ($filetype == 'jpg') {
        imagejpeg($thumbImg, "$thumbDirectory/$imageName");
    } else
    if ($filetype == 'jpeg') {
        imagejpeg($thumbImg, "$thumbDirectory/$imageName");
    } else
    if ($filetype == 'png') {
        imagepng($thumbImg, "$thumbDirectory/$imageName");
    } else
    if ($filetype == 'gif') {
        imagegif($thumbImg, "$thumbDirectory/$imageName");
    }
}
    ?>
Run Code Online (Sandbox Code Playgroud)

这是一个非常好的缩略图脚本=)这是一个例子:

$ path =原始图片所在文件夹的路径.$ name =要制作缩略图的文件的文件名.$ thumbpath =要将缩略图保存到的目录的路径.$ maxwidth = PX中缩略图的最大宽度,例如.100(将是100px).

createThumbnail($path, $name, $thumbpath, $maxwidth);