在之前的文章《PHP中的===運算符為什么比==快?》中給大家介紹了PHP中的===運算符為什么比==快,感興趣的朋友可以學習了解一下~
本文的主題則是教大家在PHP中調整JPEG圖像大小。
我們在網站開發過程中,有時會遇到要求實現縮放圖像的功能、比如封面圖、縮略圖、資料圖等等。要根據需求規定圖片的尺寸,不過大家應該也知道關于圖像大小,我們可以用HTML來修改,如下:
<img src="001.jpg" height="100" width="100" alt="圖片尺寸">
當然本文的重點是用 PHP 調整圖像大小,下面我們就直接來看代碼:
PHP代碼如下:
<?php $filename = '001.jpg'; // 最大寬度和高度 $width = 100; $height = 100; // 文件類型 header('Content-Type: image/jpg'); // 新尺寸 list($width_orig, $height_orig) = getimagesize($filename); $ratio_orig = $width_orig/$height_orig; if ($width/$height > $ratio_orig) { $width = $height*$ratio_orig; } else { $height = $width/$ratio_orig; } // 重采樣的圖像 $image_p = imagecreatetruecolor($width, $height); $image = imagecreatefromjpeg($filename); imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig); // 輸出圖像 imagejpeg($image_p, null, 100);
效果如下:

這里就需要大家掌握一個重要函數imagecopyresampled():
(該函數適用版本PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)
imagecopyresampled — 重采樣拷貝部分圖像并調整大小;
語法:
imagecopyresampled( resource $dst_image, resource $src_image, int $dst_x, int $dst_y, int $src_x, int $src_y, int $dst_w, int $dst_h, int $src_w, int $src_h ): bool
參數分別表示:
dst_image:目標圖象資源。 src_image:源圖象資源。 dst_x:目標 X 坐標點。 dst_y:目標 Y 坐標點。 src_x:源的 X 坐標點。 src_y:源的 Y 坐標點。 dst_w:目標寬度。 dst_h:目標高度。 src_w:源圖象的寬度。 src_h:源圖象的高度。
imagecopyresampled() 將一幅圖像中的一塊正方形區域拷貝到另一個圖像中,平滑地插入像素值,因此,尤其是,減小了圖像的大小而仍然保持了極大的清晰度。
In other words, imagecopyresampled() will take a rectangular area from src_image of width src_w and height src_h at position (src_x,src_y) and place it in a rectangular area of dst_image of width dst_w and height dst_h at position (dst_x,dst_y).
如果源和目標的寬度和高度不同,則會進行相應的圖像收縮和拉伸。坐標指的是左上角。本函數可用來在同一幅圖內部拷貝(如果 dst_image 和 src_image 相同的話)區域,但如果區域交迭的話則結果不可預知。
最后給大家推薦最新最全面的《PHP視頻教程》~快來學習吧!
站長資訊網