2013-08-19 105 views
11

我使用imagick進行縮略圖裁剪,但有時裁剪的縮略圖缺少圖像頂部(頭髮,眼睛)。如何在php中使用imagick? (調整大小和裁剪)

我正在考慮調整圖像大小然後裁剪。另外,我需要保持圖像大小的比例。

下面是PHP腳本我使用的作物:

$im = new imagick("img/20130815233205-8.jpg"); 
$im->cropThumbnailImage(80, 80); 
$im->writeImage("thumb/th_80x80_test.jpg"); 
echo '<img src="thumb/th_80x80_test.jpg">'; 

謝謝..

+0

你得到了什麼錯誤?什麼是預期的輸出?什麼版本的PHP?是imagick安裝?更多細節請... –

+1

不,這不是一個錯誤。 imagick工作正常。上面的腳本只會裁剪。我想首先調整大小,然後我想裁剪它,所以我錯過了第一步.. – newworroo

+0

那麼,先調用'imageResize',然後... –

回答

22

這個任務並不容易,因爲「重要」的部分可能並不總是在同一個地方。儘管如此,使用這樣的事情

$im = new imagick("c:\\temp\\523764_169105429888246_1540489537_n.jpg"); 
$imageprops = $im->getImageGeometry(); 
$width = $imageprops['width']; 
$height = $imageprops['height']; 
if($width > $height){ 
    $newHeight = 80; 
    $newWidth = (80/$height) * $width; 
}else{ 
    $newWidth = 80; 
    $newHeight = (80/$width) * $height; 
} 
$im->resizeImage($newWidth,$newHeight, imagick::FILTER_LANCZOS, 0.9, true); 
$im->cropImage (80,80,0,0); 
$im->writeImage("D:\\xampp\\htdocs\\th_80x80_test.jpg"); 
echo '<img src="th_80x80_test.jpg">'; 

(測試)

應該工作。 cropImage參數(0和0)確定裁剪區域的左上角。因此,玩這些遊戲會給你留下不同的結果。

+1

謝謝!這是完美的.. – newworroo

1

基於Martin's answer我做了重新調整和作物Imagick圖像以適合給定寬度和高度(即行爲完全爲CSS background-size: cover聲明)更一般的功能:

/** 
* Resizes and crops $image to fit provided $width and $height. 
* 
* @param \Imagick $image 
* Image to change. 
* @param int $width 
* New desired width. 
* @param int $height 
* New desired height. 
*/ 
function image_cover(Imagick $image, $width, $height) { 
    $ratio = $width/$height; 

    // Original image dimensions. 
    $old_width = $image->getImageWidth(); 
    $old_height = $image->getImageHeight(); 
    $old_ratio = $old_width/$old_height; 

    // Determine new image dimensions to scale to. 
    // Also determine cropping coordinates. 
    if ($ratio > $old_ratio) { 
    $new_width = $width; 
    $new_height = $width/$old_width * $old_height; 
    $crop_x = 0; 
    $crop_y = intval(($new_height - $height)/2); 
    } 
    else { 
    $new_width = $height/$old_height * $old_width; 
    $new_height = $height; 
    $crop_x = intval(($new_width - $width)/2); 
    $crop_y = 0; 
    } 

    // Scale image to fit minimal of provided dimensions. 
    $image->resizeImage($new_width, $new_height, imagick::FILTER_LANCZOS, 0.9, true); 

    // Now crop image to exactly fit provided dimensions. 
    $image->cropImage($new_width, $new_height, $crop_x, $crop_y); 
} 

希望這可以幫助別人。

+1

'imagick :: FILTER_LANCZOS''應該是''\ Imagick :: FILTER_LANCZOS'' –