要用 PHP 自動創建一個圖片的縮圖,做法十分簡單,因為 PHP 已內建了相關函式。本文將會介紹製作縮圖的巨體做法。 (Web Server 需要 GD 支援)
imagecopyresized
PHP 已經內建了製作縮圖的函式,它是 imagecopyresized,以下是 imagecopyresized 的語法:
int imagecopyresized ( 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 )
dst_image — 輸出目標檔案
src_image — 來源檔案
dst_x — 目標檔案開始點的 x 座標
dst_y — 目標檔案開始點的 y 座標
src_x — 來源檔案開始點的 x 座標
src_y — 來源檔案開始點的 y 座標
dst_w — 目標檔案的長度
dst_h — 目標檔案的高度
src_w — 來源檔案的長度
src_h — 來源檔案的高度
例如上傳的檔案是 $_FILES[‘pic’],而它是屬於 jpeg 圖案,縮圖的長及高不大於 100,那麼實作方法如下:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<?php $src = imagecreatefromjpeg($_FILES['pic']['tmp_name']); // get the source image's widht and hight $src_w = imagesx($src); $src_h = imagesy($src); // assign thumbnail's widht and hight if ($src_w > $src_h) { $thumb_w = 100; $thumb_h = intval($src_h / $src_w * 100); } else { $thumb_h = 100; $thumb_w = intval($src_w / $src_h * 100); } // if you are using GD 1.6.x, please use imagecreate() $thumb = imagecreatetruecolor($thumb_w, $thumb_h); // start resize imagecopyresized($thumb, $src, 0, 0, 0, 0, $thumb_w, $thumb_h, $src_w, $src_h); // save thumbnail imagejpeg($thumb, "/var/www/html/uploads/thumb/".$_FILES['pic']['name']); ?> |
以上的程式大致上是先取得 $_FILES[‘pic’] 圖檔的長度及高度,然後再計算出縮圖的相應長度及高度,製作好縮圖後,最後將縮圖儲存到 /var/www/html/uploads/thumb/ 目錄下。
高精度圖片的質量以上製作縮圖的方法在處理一般圖檔是沒有問題,但當要處理的是高精度圖片,那麼造出的縮圖會很難看,與繪圖軟件造出的縮圖有很大程度上的分別,要解決這個問題,可以使用在 php.net 上用戶貼出的一個函式,這個函式可以解決高精度圖片的問題,但換來的代價是處理的時間較慢:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<?php function ImageResize (&$src, $x, $y) { $dst=imagecreatetruecolor($x, $y); $pals=ImageColorsTotal ($src); for ($i=0; $i<$pals; $i++) { $colors=ImageColorsForIndex ($src, $i); ImageColorAllocate ($dst, $colors['red'], $colors['green'], $colors['blue']); } $scX =(imagesx ($src)-1)/$x; $scY =(imagesy ($src)-1)/$y; $scX2 =intval($scX/2); $scY2 =intval($scY/2); for ($j = 0; $j < ($y); $j++) { $sY = intval($j * $scY); $y13 = $sY + $scY2; for ($i = 0; $i < ($x); $i++) { $sX = intval($i * $scX); $x34 = $sX + $scX2; $c1 = ImageColorsForIndex ($src, ImageColorAt ($src, $sX, $y13)); $c2 = ImageColorsForIndex ($src, ImageColorAt ($src, $sX, $sY)); $c3 = ImageColorsForIndex ($src, ImageColorAt ($src, $x34, $y13)); $c4 = ImageColorsForIndex ($src, ImageColorAt ($src, $x34, $sY)); $r = ($c1['red']+$c2['red']+$c3['red']+$c4['red'])/4; $g = ($c1['green']+$c2['green']+$c3['green']+$c4['green'])/4; $b = ($c1['blue']+$c2['blue']+$c3['blue']+$c4['blue'])/4; ImageSetPixel ($dst, $i, $j, ImageColorClosest ($dst, $r, $g, $b)); } } return ($dst); } ?> |
以上函式的用法相檔簡單,$src 是來源檔案,$x 是縮圖的長度,$y 是縮圖的高度,回傳的是縮圖。
而在 PHP 中除了使用 GD 外,還可以用 ImageMagick 來做,而 ImageMagick 日後有機會再作介紹。