在之前的文章《PHP中的===運(yùn)算符為什么比==快?》中給大家介紹了PHP中的===運(yùn)算符為什么比==快,感興趣的朋友可以學(xué)習(xí)了解一下~
本文的主題則是教大家在PHP中調(diào)整JPEG圖像大小。
我們?cè)诰W(wǎng)站開(kāi)發(fā)過(guò)程中,有時(shí)會(huì)遇到要求實(shí)現(xiàn)縮放圖像的功能、比如封面圖、縮略圖、資料圖等等。要根據(jù)需求規(guī)定圖片的尺寸,不過(guò)大家應(yīng)該也知道關(guān)于圖像大小,我們可以用HTML來(lái)修改,如下:
<img src="001.jpg" height="100" width="100" alt="圖片尺寸">
當(dāng)然本文的重點(diǎn)是用 PHP 調(diào)整圖像大小,下面我們就直接來(lái)看代碼:
PHP代碼如下:
<?php $filename = '001.jpg'; // 最大寬度和高度 $width = 100; $height = 100; // 文件類(lèi)型 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);
效果如下:
這里就需要大家掌握一個(gè)重要函數(shù)imagecopyresampled()
:
(該函數(shù)適用版本PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)
imagecopyresampled
— 重采樣拷貝部分圖像并調(diào)整大??;
語(yǔ)法:
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
參數(shù)分別表示:
dst_image:目標(biāo)圖象資源。 src_image:源圖象資源。 dst_x:目標(biāo) X 坐標(biāo)點(diǎn)。 dst_y:目標(biāo) Y 坐標(biāo)點(diǎn)。 src_x:源的 X 坐標(biāo)點(diǎn)。 src_y:源的 Y 坐標(biāo)點(diǎn)。 dst_w:目標(biāo)寬度。 dst_h:目標(biāo)高度。 src_w:源圖象的寬度。 src_h:源圖象的高度。
imagecopyresampled() 將一幅圖像中的一塊正方形區(qū)域拷貝到另一個(gè)圖像中,平滑地插入像素值,因此,尤其是,減小了圖像的大小而仍然保持了極大的清晰度。
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).
如果源和目標(biāo)的寬度和高度不同,則會(huì)進(jìn)行相應(yīng)的圖像收縮和拉伸。坐標(biāo)指的是左上角。本函數(shù)可用來(lái)在同一幅圖內(nèi)部拷貝(如果 dst_image 和 src_image 相同的話)區(qū)域,但如果區(qū)域交迭的話則結(jié)果不可預(yù)知。
最后給大家推薦最新最全面的《PHP視頻教程》~快來(lái)學(xué)習(xí)吧!