2015-02-23 212 views
1

我剛開始使用PHP的Imageick庫。PHP Imagick - 中心裁剪後的圖像

我開始通過修剪一個用戶的圖像,像這樣:

$img_path = 'image.jpg'; 
$img = new Imagick($img_path); 
$img_d = $img->getImageGeometry(); 
$img_w = $img_d['width']; 
$img_h = $img_d['height']; 

$crop_w = 225; 
$crop_h = 430; 

$crop_x = ($img_w - $crop_w)/2; 
$crop_y = ($img_h - $crop_h)/2; 
$img->cropImage($img_w, $img_h, $crop_x, $crop_y); 

我現在需要的225 X 430裁剪圖像放置到一個新的形象,在500像素X 500像素的中心。新圖像必須具有透明背景。像這樣(灰色邊框僅是視覺):

enter image description here

我該怎麼辦呢?我已經試過2種選擇:

compositeImage()

$trans = '500x500_empty_transparent.png'; 
$holder = new Imagick($trans); 
$holder->compositeImage($img, imagick::COMPOSITE_DEFAULT, 0, 0); 

通過在500x500px做什麼也沒有上一個透明的PNG我希望我可以使用compositeImage把圖像最重要的是。它這樣做,但不保留$holder的原始大小,但使用的225x430大小

frameImage()

$frame_w = (500 - $w)/2; 
$frame_h = (500 - $h)/2; 
$img->frameimage('', $frame_w, $frame_h, 0, 0); 

我創建了一個邊界,構成了圖像的剩餘像素,使500 x500px。我希望通過將第一個colour參數留空,它將是透明的,但它會創建淺灰色背景,因此不透明。

我該如何做到這一點?

回答

1

如果您只想要透明背景,則不需要單獨的圖像文件。裁剪圖像並調整大小。

<?php 
header('Content-type: image/png'); 

$path = 'image.jpg'; 
$image = new Imagick($path); 
$geometry = $image->getImageGeometry(); 

$width = $geometry['width']; 
$height = $geometry['height']; 

$crop_width = 225; 
$crop_height = 430; 
$crop_x = ($width - $crop_width)/2; 
$crop_y = ($height - $crop_height)/2; 

$size = 500; 

$image->cropImage($crop_width, $crop_height, $crop_x, $crop_y); 
$image->setImageFormat('png'); 
$image->setImageBackgroundColor(new ImagickPixel('transparent')); 
$image->extentImage($size, $size, -($size - $crop_width)/2, -($size - $crop_height)/2); 

echo $image; 

使用setImageFormat將圖像轉換到PNG(以允許透明性),然後設置一個透明背景setImageBackgroundColor。最後,使用extentImage來調整它的大小。

+0

現貨,謝謝你的答案和完整的例子 – 2015-02-23 16:43:19