星期日, 七月 02, 2006
PHP 縮圖
因為本 blog 的頻寬有限, 想要貼圖又不太敢貼, 所以我的 blog 一直都很少有在貼圖(放在 flickr 或 其它地方 又怕何時不見了就麻煩了).
今天為了要貼一張圖, 但是看 166kb 實在蠻大的, Gimp 等的縮圖縮起來又糢糊不清(應該是我不會用.. Orz), 還是自己寫個簡單的縮圖比較簡單~ :)
總之效果還不錯就好了~
檔案名稱: img_resize.php
<?php /** * Usage: * php img_resize.php filename.png > xxx.png * php img_resize.php filenmae.jpg > xxx.jpg * php img_resize.php filenmae.gif > xxx.gif * * Author: Tsung * URL: http://plog.longwin.com.tw/files/img_resize.phps */ $percent = 0.5; // get filename $filename = $argv[1]; // get sub filename, ex: jpg,jpeg,png,gif $sub_name = trim( substr($filename, -4), '.' ); if( $sub_name == 'jpg' ) { // jpg use jpeg header & function $sub_name='jpeg'; } // Content type, ex: header('Content-type: image/jpeg'); header('Content-type: image/'.$sub_name); // Get new dimensions list($width, $height) = getimagesize($filename); $new_width = $width * $percent; $new_height = $height * $percent; // Resample $image_p = imagecreatetruecolor($new_width, $new_height); // $function_name: set function name // imagecreatefromjpeg, imagecreatefrompng, imagecreatefromgif $function_name = 'imagecreatefrom'.$sub_name; $image = $function_name($filename); //$image = imagecreatefromjpeg($filename); imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); // Output imagejpeg($image_p, null, 100); ?>
使用方法:
- php img_resize.php filename.png > xxx.png
- php img_resize.php filenmae.jpg > xxx.jpg
- php img_resize.php filenmae.gif > xxx.gif
使用函式:
- bool 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 )
- bool 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 )
函式參數說明:
- 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(), imagecopyresized() 兩個的縮圖品質, imagecopyresampled() 縮起來比較好.
也可以用 imagemagick 喔
有裝 imagemagick 的話 可以考慮使用 convert 這個工具
裡面有 resize 的選項可以用
回 letoh
我忘記有這個東西可以用了... XD
不過"據說", 好像 imagecopyresampled 圖片看起來的效果會比 convert 好.
有空再來測試比較看看 :)
resampling
當然,resize 時有做 resample 的話品質會好很多,例如內插或積分法
convert 也有相關參數
-resample geometry change the resolution of an image
-sample geometry scale image with pixel sampling
不過我沒有實驗過怎麼搭配可以得出比較好的品質,如果 Tsung 有興趣的話可以試試看:)
回 jiing
嗯嗯~ 沒錯, 當初在寫這隻的時後, 主要是拿來當自己的 command line 用的, 可以參考之後寫的這隻看看:
http://plog.longwin.com.tw/programming/2007/08/20/php_image_resize_2007
發表迴響
PS2: 若您的留言被誤判, 我都會再自行看過, 不需要一直重覆張貼~





