溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

php壓縮圖片失敗如何解決

發(fā)布時間:2023-03-24 15:58:31 來源:億速云 閱讀:192 作者:iii 欄目:編程語言

本文小編為大家詳細介紹“php壓縮圖片失敗如何解決”,內(nèi)容詳細,步驟清晰,細節(jié)處理妥當(dāng),希望這篇“php壓縮圖片失敗如何解決”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學(xué)習(xí)新知識吧。

首先,我嘗試在代碼中使用imagejpeg函數(shù)來壓縮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);
?>

盡管我嘗試了各種不同的壓縮質(zhì)量,但最終生成的圖像總是比原始圖像更大,而不是更小。我嘗試了不同的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。這個函數(shù)實際上生成了一個新的圖像副本,而不是真正的壓縮原始圖像。因此,使用該函數(shù)會導(dǎo)致生成的圖像比原始圖像更大。

為了解決這個問題,我改用imagecopyresampled函數(shù),該函數(shù)可以在不生成新的圖像副本的情況下壓縮原始圖像。以下是我修改后成功的代碼:

<?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);
?>

現(xiàn)在,通過使用imagecopyresampled函數(shù),我可以輕松地壓縮JPEG、PNG和WebP圖像,而不會出現(xiàn)壓縮失敗的問題。我希望我的經(jīng)驗?zāi)軌驇椭渌鸚eb開發(fā)人員避免在圖像處理中遇到相同的問題。

讀到這里,這篇“php壓縮圖片失敗如何解決”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識點還需要大家自己動手實踐使用過才能領(lǐng)會,如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

php
AI