php压缩图片失败如何解决

后端开发   发布日期:2023年11月06日   浏览次数:139

本文小编为大家详细介绍“php压缩图片失败如何解决”,内容详细,步骤清晰,细节处理妥当,希望这篇“php压缩图片失败如何解决”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

首先,我尝试在代码中使用imagejpeg函数来压缩JPEG图像。以下是我尝试的代码:

<?php
// Load the image
$image = imagecreatefromjpeg('image.jpg');

// Resize the image
$resizedImage = imagescale($image, 200);

// Compress and save the image
imagejpeg($resizedImage, 'compressed.jpg', 80);
?>

尽管我尝试了各种不同的压缩质量,但最终生成的图像总是比原始图像更大,而不是更小。我尝试了不同的JPEG库版本,但仍然无济于事。

接下来,我开始尝试使用其他图像格式,如PNG和WebP。我使用以下代码来压缩PNG图像:

<?php
// Load the image
$image = imagecreatefrompng('image.png');

// Resize the image
$resizedImage = imagescale($image, 200);

// Compress and save the image
imagepng($resizedImage, 'compressed.png', 9);
?>

但是,我再次遇到了同样的问题 - 生成的图像比原始图像更大。

最后,我尝试了Google的WebP格式,以期降低图像大小。我使用libwebp库和以下代码来压缩图像:

<?php
// Load the image
$image = imagecreatefromjpeg('image.jpg');

// Resize the image
$resizedImage = imagescale($image, 200);

// Convert the image to WebP format
imagewebp($resizedImage, 'compressed.webp', 80);
?>

遗憾的是,即使是使用WebP格式,我也无法成功压缩图像。

在多次尝试之后,我终于找到了解决方案。问题出在我在代码中使用了

imagescale
。这个函数实际上生成了一个新的图像副本,而不是真正的压缩原始图像。因此,使用该函数会导致生成的图像比原始图像更大。

为了解决这个问题,我改用

imagecopyresampled
函数,该函数可以在不生成新的图像副本的情况下压缩原始图像。以下是我修改后成功的代码:

<?php
// Load the image
$image = imagecreatefromjpeg('image.jpg');

// Get the original dimensions of the image
$width = imagesx($image);
$height = imagesy($image);

// Calculate the new dimensions of the image
$newWidth = 200;
$newHeight = $height * ($newWidth / $width);

// Create a new image with the new dimensions
$resizedImage = imagecreatetruecolor($newWidth, $newHeight);

// Copy and resample the original image into the new image
imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

// Compress and save the image
imagejpeg($resizedImage, 'compressed.jpg', 80);
?>

现在,通过使用

imagecopyresampled
函数,我可以轻松地压缩JPEG、PNG和WebP图像,而不会出现压缩失败的问题。我希望我的经验能够帮助其他Web开发人员避免在图像处理中遇到相同的问题。

以上就是php压缩图片失败如何解决的详细内容,更多关于php压缩图片失败如何解决的资料请关注九品源码其它相关文章!