调整图像大小并放置在画布中心

4

我正在尝试在iMagick中完成以下操作,但无法使其正常工作:

检查图像高度是否超过390像素,如果是,则将其调整为390像素高,如果不是,则保持其原始尺寸。

添加一个白色画布,宽度为300像素,高度为400像素,然后将图像置于其中心位置。

我的代码如下:

$im = new Imagick("test.jpg");
$imageprops = $im->getImageGeometry();
$width = $imageprops['width'];
$height = $imageprops['height'];
if($height > '390'){
$newHeight = 390;
$newWidth = (390 / $height) * $width;
}else{
$newWidth = $imageprops['width'];
$newHeight = $imageprops['height'];
}

$im->resizeImage($newWidth,$newHeight, Imagick::FILTER_LANCZOS, 0.9, true);

$canvas = new Imagick();
$canvas->newImage(300, 400, 'white', 'jpg');
$canvas->compositeImage($im, Imagick::COMPOSITE_OVER, 100, 50);

$canvas->writeImage( "test-1.jpg" );

当图像被生成时,由于某种原因,大的图像会缩放至388像素高度而小的图像则保持其原始尺寸。
虽然在大型图像上添加100、50后可以正常放置在画布上,但放置位置始终不正确。
大多数图像都是高而瘦的,但也有一些比它们高宽比更大。
请问我做错了哪些地方?
谢谢,
Rick

您可能会发现将重力设置为CENTER,将背景颜色设置为白色,然后使用setImageExtent()将图像放在300x400的白色画布上会更容易。 - Mark Setchell
如果($height>390) - Mark Setchell
1个回答

7

Mark的建议可能是更好的选择。Extent尊重重力,并确保最终图像始终为300x400。如果要使用Imagick::compositeImage将图像放置在中心,您需要计算偏移量--这很容易,因为您已经拥有主题和画布图像的宽度/高度。

$canvas = new Imagick();
$finalWidth = 300;
$finalHeight = 400;
$canvas->newImage($finalWidth, $finalHeight, 'white', 'jpg' );
$offsetX = (int)($finalWidth  / 2) - (int)($newWidth  / 2);
$offsetY = (int)($finalHeight / 2) - (int)($newHeight / 2);
$canvas->compositeImage( $im, imagick::COMPOSITE_OVER, $offsetX, $offsetY );

1
您可以使用重力替换计算:$canvas->compositeImageGravity($over, Imagick::COMPOSITE_OVER, Imagick::GRAVITY_CENTER); - Krzysiek

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接