php压缩图片失败如何解决

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

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

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

  1. <?php
  2. // Load the image
  3. $image = imagecreatefromjpeg('image.jpg');
  4. // Resize the image
  5. $resizedImage = imagescale($image, 200);
  6. // Compress and save the image
  7. imagejpeg($resizedImage, 'compressed.jpg', 80);
  8. ?>

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

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

  1. <?php
  2. // Load the image
  3. $image = imagecreatefrompng('image.png');
  4. // Resize the image
  5. $resizedImage = imagescale($image, 200);
  6. // Compress and save the image
  7. imagepng($resizedImage, 'compressed.png', 9);
  8. ?>

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

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

  1. <?php
  2. // Load the image
  3. $image = imagecreatefromjpeg('image.jpg');
  4. // Resize the image
  5. $resizedImage = imagescale($image, 200);
  6. // Convert the image to WebP format
  7. imagewebp($resizedImage, 'compressed.webp', 80);
  8. ?>

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

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

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

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

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

  1. <?php
  2. // Load the image
  3. $image = imagecreatefromjpeg('image.jpg');
  4. // Get the original dimensions of the image
  5. $width = imagesx($image);
  6. $height = imagesy($image);
  7. // Calculate the new dimensions of the image
  8. $newWidth = 200;
  9. $newHeight = $height * ($newWidth / $width);
  10. // Create a new image with the new dimensions
  11. $resizedImage = imagecreatetruecolor($newWidth, $newHeight);
  12. // Copy and resample the original image into the new image
  13. imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
  14. // Compress and save the image
  15. imagejpeg($resizedImage, 'compressed.jpg', 80);
  16. ?>

现在,通过使用

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

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