php压缩图片失败怎么解决

PHPz
PHPz 原创
2023-03-24 15:18:02 764浏览

PHP是一种流行的Web编程语言,其在图像处理领域也占有重要地位。尽管PHP自带了很多图像处理函数,但在我最近的项目中,我遇到了一个令人沮丧的问题 - 图片压缩失败。

在这个项目中,我需要将用户上传的图片压缩到指定的尺寸和质量,以便在Web应用程序中进行展示。为了实现这一目标,我使用了PHP GD库中的图像处理函数。但是,即使我遵循了所有推荐的最佳做法,如设置内存限制、检查图像格式和使用最新的库版本,但是我仍无法成功压缩图像。

首先,我尝试在代码中使用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中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。