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: https://blogs.longwin.com.tw/lifetype/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 (strtolower($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() 縮起來比較好.

參考: PHP: imagecopyresampled - Manual

作者: Tsung

對新奇的事物都很有興趣, 喜歡簡單的東西, 過簡單的生活.

在〈PHP 縮圖〉中有 13 則留言

  1. 我忘記有這個東西可以用了... XD
    不過"據說", 好像 imagecopyresampled 圖片看起來的效果會比 convert 好.
    有空再來測試比較看看 🙂

  2. 當然,resize 時有做 resample 的話品質會好很多,例如內插或積分法
    convert 也有相關參數
    -resample geometry change the resolution of an image
    -sample geometry scale image with pixel sampling
    不過我沒有實驗過怎麼搭配可以得出比較好的品質,如果 Tsung 有興趣的話可以試試看:)

  3. 要如何上傳jpg後
    縮圖時可以依較長的邊縮為120像素(等比例縮)
    處理過的圖片也會另儲存起來
    (web上會有一個原檔和另一個縮圖的檔)
    謝謝

  4. 要如何上傳jpg後
    縮圖時可以依較長的邊縮為120像素(等比例縮)
    處理過的圖片也會另儲存起來
    (web上會有一個原檔和另一個縮圖的檔)
    謝謝

lin 發表迴響取消回覆

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料