如何在 PHP 中将 ImageMagick 命令转换为 Imagick?

How to translate ImageMagick command to Imagick in PHP?

我试过翻译,但是不行,没有人知道错在哪里吗?

ImageMagick

convert source.jpg \( -size 640x480 xc:white -size 200x200 
xc:black -geometry +200+100 -compose over -composite \) 
+geometry -alpha off -compose copy_opacity -composite result.png

PHP 我试过使用 Imagick 的代码,但没有成功:

//Open your image and get its dimensions
$image = new Imagick('source.png');
$height = $image->getImageHeight();
$width = $image->getImageWidth();

//Create a new transparent image of the same size
$mask = new Imagick();
$mask->newImage($width, $height, new ImagickPixel('white'));

//Draw onto the new image the areas you want to be transparent in the original
$draw = new ImagickDraw();
$draw->setFillColor('black'); 
$draw->rectangle($x, $y, $x + 200, $y + 200);
$mask->drawImage( $draw );

//Composite the images
$image->compositeImage($mask, Imagick::COMPOSITE_COPYOPACITY, 0, 0, Imagick::CHANNEL_ALPHA);
$image->setImageFormat('png');
$image->writeImage("~/images/result.png");

原题:

另一个尝试

$width = 256;
$height = 256;
$x = 50;
$y = 100;
$fooWidth = 100;
$fooHeight = 60;


$image = new Imagick();
$image->newImage($width, $height, new ImagickPixel('yellow'));


//Create a new transparent image of the same size
$mask = new Imagick();
$mask->newImage($width, $height, new ImagickPixel('white'));
$mask->setImageFormat('png');

//Draw onto the new image the areas you want to be transparent in the original
$draw = new ImagickDraw();
$draw->setFillColor('black');
$draw->rectangle($x, $y, $x + $fooWidth, $y + $fooHeight);
$mask->drawImage($draw);

//Composite the images
$image->compositeImage($mask, Imagick::COMPOSITE_COPYOPACITY, 0, 0);

$image->setImageFormat('png');
$image->writeImage($path);

COMPOSITE_COPYOPACITY 看起来不行:

首先,您要绘制一个具有相同坐标的矩形。你需要让它们不同才能得到一个矩形。

$draw->rectangle( 200, 100, 200, 100 );

应该更像

 $draw->rectangle( 100, 100, 200, 200 )

这将在 100,100 的左上角和 200,200 的右下角绘制一个矩形。所以矩形的大小为 100x100。

如果你想让它像我的命令行示例,那么做

$draw->rectangle( 200, 100, 400, 300 );

那将是 200,100 的左上角和 400,300 的右下角,因此大小为 200x200。

其次,您没有指定输出格式。如果您正在写入 JPG,它不支持透明度。因此请务必使用 PNG 或 TIF 进行输出。

尝试在创建遮罩时最后关闭 alpha。这对我来说很好用:

convert -size 500x500 xc:yellow \( -size 500x500 xc:white -fill black -draw "rectangle 100,100 300,300" -alpha off \) -compose copy_opacity -composite result.png

请参阅 http://us3.php.net/manual/en/imagick.setimagematte.php,其中示例添加了

$mask->setImageMatte(false);

绘制命令之后和 compositeImage() 命令之前