PHP Imagick负偏移裁剪图像并保留负空间

5
我正在使用php Imagick::cropImage,但遇到了一些问题。
假设我有这张图片: Test Image 我想用这个裁剪区域来裁剪图像: Image Crop Area 这是我正在使用的PHP代码:
$width = 200;
$height = 200;
$x = -100;
$y = -50;

$image = new Imagick();
$image->readImage($path_to_image);
$image->cropImage( $width, $height, $x, $y );
$image->writeImage($path_to_image);
$image->clear();
$image->destroy();

结果是一个50px x 150px的图片(这不是我想要的): Image Crop Result 我想要的是一个200px x 200px的图片,并用α通道填充其余部分(棋盘图案表示透明像素): Image Crop Desired Result 如何填充这些空白像素?
1个回答

8
使用Imagick::extentImage函数,在裁剪后将图像扩展到所需的大小。可以通过设置背景颜色或根据需要进行泛洪填充来轻松地填充“空”像素。请参考Imagick::extentImage
$width = 100;
$height = 100;
$x = -50;
$y = -25;

$image = new Imagick();
$image->readImage('rose:');
$image->cropImage( $width, $height, $x, $y );
$image->extentImage( $width, $height, $x, $y );

负偏移裁剪

用背景填充空白像素

$image = new Imagick();
$image->readImage('rose:');
$image->setImageBackgroundColor('orange');
$image->cropImage( $width, $height, $x, $y );
$image->extentImage( $width, $height, $x, $y );

填充背景颜色

或者使用ImagickDraw

$image = new Imagick();
$image->readImage('rose:');
$image->cropImage( $width, $height, $x, $y );
$image->extentImage( $width, $height, $x, $y );

$draw = new ImagickDraw();
$draw->setFillColor('lime');
$draw->color(0, 0, Imagick::PAINT_FLOODFILL);
$image->drawImage($draw);

填充绘制

编辑

若要设置透明的空像素,请在背景颜色之前设置遮罩。

$image->setImageMatte(true);
$image->setImageBackgroundColor('transparent');

啊哈!我发现有一种简单的方法可以做到。感谢您的出色回复!如果我想用透明像素填充背景怎么办?我尝试了 $image->setBackgroundColor(new ImagickPixel('transparent')); 但没有成功(像素是白色的)- 文件格式是 .png。我甚至添加了 $image->setImageFormat("png32"); 确保它是 png 格式。 - ctown4life
啊,要实现透明效果,您需要在设置背景颜色之前启用蒙版。我会更新我的答案。 - emcconville
太好了!那个可行。再次感谢你的帮助和时间。 - ctown4life
可爱的解决方案。谢谢你救了我的一天。+1 - Gogol

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