先給大家炫下效果圖,如果大家覺得還很滿意,請繼續往下閱讀:
這裡說的imagick 是 ImageMagick 在PHP下的擴充。用pecl安裝起來那叫一個輕鬆簡單一條指令就搞定:
複製程式碼 程式碼如下:
sudo pecl install imagick
sudo pecl install imagick
上extension=imagick.so,然後記得重啟apache或php-fpm服務。
這個需求是要這樣產生縮圖:
4.如果有4張圖片,則像田字格一樣平均分配空間;
5.更多張圖片,則只取前4張,以田字格方式產生縮圖。
namespace \clarence\thumbnail; class Thumbnail extends \Imagick { /** * @param array $images * @param int $width * @param int $height * @return static * @throws ThumbnailException */ public static function createFromImages($images, $width, $height){ if (empty($images)){ throw new ThumbnailException("No images!"); } $thumbnail = new static(); $thumbnail->newImage($width, $height, 'white', 'jpg'); $thumbnail->compositeImages($images); return $thumbnail; } public function compositeImages($images){ $imagesKeys = array_keys($images); $compositeConfig = $this->calcCompositeImagesPosAndSize($images); foreach ($compositeConfig as $index => $cfg){ $imgKey = $imagesKeys[$index]; $img = new \Imagick($images[$imgKey]); $img = $this->makeCompositeThumbnail($img, $cfg); $this->compositeImage($img, self::COMPOSITE_OVER, $cfg['to']['x'], $cfg['to']['y']); } } protected function makeCompositeThumbnail(\Imagick $img, $cfg){ $img->cropThumbnailImage($cfg['size']['width'], $cfg['size']['height']); return $img; } protected function calcCompositeImagesPosAndSize($images){ $width = $this->getImageWidth(); $height = $this->getImageHeight(); switch(count($images)){ case 0: throw new ThumbnailException("No images!"); case 1: // | 0 | return [ 0 => [ 'to' => [ 'x' => 0, 'y' => 0 ], 'size' => [ 'width' => $width, 'height' => $height, ] ] ]; case 2: // | 0 | 1 | return [ 0 => [ 'to' => [ 'x' => 0, 'y' => 0 ], 'size' => [ 'width' => $width / 2, 'height' => $height, ] ], 1 => [ 'to' => [ 'x' => $width / 2, 'y' => 0], 'size' => [ 'width' => $width / 2, 'height' => $height, ] ] ]; case 3: // | 0 | 1 | // | 2 | | return [ 0 => [ 'to' => [ 'x' => 0, 'y' => 0 ], 'size' => [ 'width' => $width / 2, 'height' => $height / 2, ] ], 1 => [ 'to' => [ 'x' => $width / 2, 'y' => 0], 'size' => [ 'width' => $width / 2, 'height' => $height, ] ], 2 => [ 'to' => [ 'x' => 0, 'y' => $height / 2 ], 'size' => [ 'width' => $width / 2, 'height' => $height / 2, ] ], ]; default: // >= 4: // | 0 | 1 | // | 2 | 3 | return [ 0 => [ 'to' => [ 'x' => 0, 'y' => 0 ], 'size' => [ 'width' => $width / 2, 'height' => $height / 2, ] ], 1 => [ 'to' => [ 'x' => $width / 2, 'y' => 0], 'size' => [ 'width' => $width / 2, 'height' => $height / 2, ] ], 2 => [ 'to' => [ 'x' => 0, 'y' => $height / 2 ], 'size' => [ 'width' => $width / 2, 'height' => $height / 2, ] ], 3 => [ 'to' => [ 'x' => $width / 2, 'y' => $height / 2], 'size' => [ 'width' => $width / 2, 'height' => $height / 2, ] ], ]; } } }
用個試試看:
: $thumbnail = clarencethumbnailThumbnail::createFromImages($srcImages, 240, 320);
$thumbnail->writeImage($outputDir."/example.jpg");略圖的相關知識,希望對大家有幫助!
以上就介紹了PHP利用imagick產生組合縮圖,包含了方面的內容,希望對PHP教學有興趣的朋友有幫助。