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

时间:2017-10-28 02:03:41

标签: php imagemagick imagick

我试图翻译它,但不起作用,没有人知道错误是什么吗?

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

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

//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");

原始问题:

How to make specified area of an image transparent with Imagick?

另一次尝试

$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看起来不起作用:

enter image description here

2 个答案:

答案 0 :(得分:1)

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

$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作为输出。

答案 1 :(得分:1)

尝试在创建蒙版时将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

enter image description here

请参阅示例添加的http://us3.php.net/manual/en/imagick.setimagematte.php

$mask->setImageMatte(false);

在draw命令之后和compositeImage()命令之前