[英]how do i use imagick in php? (resize & crop)
我使用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">';
謝謝..
這個任務並不容易,因為“重要”部分可能並不總是在同一地方。 還是用這樣的東西
$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)確定裁剪區域的左上角。 因此,使用這些功能可以為您保留圖像中保留的內容的不同結果。
根據Martin的回答,我做了一個更通用的功能,可以調整Imagick
圖像的大小並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);
}
希望這可以對某人有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.