【问题标题】:Resize image and place in center of canvas调整图像大小并放置在画布中心
【发布时间】:2017-03-14 10:33:37
【问题描述】:

我正在 iMagick 中尝试执行以下操作,但无法正常工作:

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

添加一个 300px 宽 x 400px 高的白色画布,然后将图像放在画布的中心。

我的代码是:

$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 的大图像上确实有效。

大多数图像又高又瘦,但也有一些图像比高宽。

任何想法我哪里出错了?

谢谢,

瑞克

【问题讨论】:

  • 您可能会发现将重力设置为 CENTER,将背景颜色设置为白色,然后使用 setImageExtent() 将图像放在 300x400 的白色画布上会更容易。
  • if($height>390) 不带引号。

标签: php imagemagick imagick


【解决方案1】:

Mark 的 cmets 可能是更好的选择。范围尊重重力,并确保最终图像始终为 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 );

【讨论】:

  • 可以用重力代替计算:$canvas->compositeImageGravity($over, Imagick::COMPOSITE_OVER, Imagick::GRAVITY_CENTER);
猜你喜欢
  • 1970-01-01
  • 2012-08-27
  • 2017-04-29
  • 2011-01-19
  • 2017-04-22
  • 2013-03-24
  • 2014-05-07
  • 2011-05-09
相关资源
最近更新 更多