phpThumbnailerで背景を埋める処理

11月 18th, 2008 admin Posted in PHP | No Comments »

Index of /projects/phpThumbnailer
というPHPで画像のリサイズをしてくれるライブラリがあって、これが1ファイルでできている上にリサイズするだけなら

PHP:
  1. <?
  2. include("../class.Thumbnail.php");
  3. $tn_image = new Thumbnail("sample.jpg", 0, 0, 25);
  4. $tn_image->save("tn_sample.jpg");
  5. ?>

というシンプルさなのでとても重宝しています。
使い方とか、キャッシュをする方法は以前書いたのでこちらをご覧下さい。

Webアプリには必要十分なのですが唯一つ、画像のリサイズで空白を埋めるというのをやってほしかったので拡張をしました。
たとえばw100xh50の画像を50x50にリサイズしたときに、結果として50x25の画像を受け取るのではなく、50x50の画像ができあがって、縦の足りない部分は背景色を表示するというような感じです。

thumbnail.inc.phpに下記のメソッドを追加して使ってください。

PHP:
  1. /**
  2.      * Resizes image to maxWidth x maxHeight
  3.      *
  4.      * @param int $maxWidth
  5.      * @param int $maxHeight
  6.      * @param string $color
  7.      */
  8.     function resizeFar($maxWidth = 0, $maxHeight = 0, $color = "FFFFFF") {
  9.         $this->resize($maxWidth, $maxHeight);
  10.  
  11.         if($maxWidth> $this->currentDimensions['width'] || $maxHeight> $this->currentDimensions['height']){
  12.             if(function_exists("ImageCreateTrueColor")) {
  13.                 $this->workingImage = ImageCreateTrueColor($maxWidth, $maxHeight);
  14.             }else {
  15.                 $this->workingImage = ImageCreate($maxWidth, $maxHeight);
  16.             }
  17.             $color = imagecolorallocate($this->workingImage, hexdec('0x' . $color{0} . $color{1}), hexdec('0x' . $color{2} . $color{3}), hexdec('0x' . $color{4} . $color{5}));
  18.             imageFill($this->workingImage,0,0,$color);
  19.  
  20.             ImageCopy(
  21.                 $this->workingImage,
  22.                 $this->newImage,
  23.                 ($maxWidth - $this->currentDimensions['width']) / 2,
  24.                 ($maxHeight - $this->currentDimensions['height']) / 2,
  25.                 0,
  26.                 0,
  27.                 $this->currentDimensions['width'],
  28.                 $this->currentDimensions['height']
  29.             );
  30.             $this->newImage = $this->workingImage;
  31.         $this->currentDimensions['width'] = $maxWidth;
  32.         $this->currentDimensions['height'] = $maxHeight;
  33.         }
  34.     }

Leave a Reply