温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

php压缩图片失败如何解决

发布时间:2023-03-24 15:58:31 来源:亿速云 阅读:143 作者:iii 栏目:编程语言

本文小编为大家详细介绍“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压缩图片失败如何解决”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php
AI