2013-08-19 7 views
11

私はサムネイルトリミングにimagickを使用しますが、トリミングされたサムネイルに画像の上部(髪、目)が欠けていることがあります。PHPでimagickを使うにはどうすればいいですか? (サイズ変更とクロップ)

私は画像のサイズを変更してからそれを切り取ることを考えていました。また、画像サイズの比率を維持する必要があります。

$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

このタスクは簡単ではありません。

以下は、私が作物に使用するPHPスクリプトです。それでも、この

$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)は、切り取り領域の左上隅を決定します。だから彼らと一緒に遊ぶことは、あなたがイメージに残っているもののdiffernt結果を与える。これは、誰かを助けるかもしれない

/** 
* 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

ありがとう!!!完璧です。 – newworroo

1

Martin's answerに基づいて、私は(つまりは正確にCSS background-size: cover宣言として振舞う)指定された幅と高さに合わせて作物にImagick画像のサイズを変更し、より一般的な機能を作りました。

+1

'' imagick :: FILTER_LANCZOS''は '' \ Imagick :: FILTER_LANCZOS''でなければなりません。 –

関連する問題