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

坚强是说给别人听的谎言 提交于 2020-03-05 03:32:42

问题


I want to make a part of an image transparent, I tried the code below, even tried many constants as COMPOSITE_DSTOUT, but all didn't work, does anyone know how to?

$fooImage->newImage(256, 256, new ImagickPixel('transparent'));
$Image->compositeImage($fooImage, Imagick::COMPOSITE_DSTOUT, $offsetX, offsetY);

I tested the code below, just got yellow with black, not transparent:

$width = 256;
$height = 256;

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

$x = 50;
$y = 100;
$fooWidth = 100;
$fooHeight = 60;

//Create a new transparent image of the same size
$mask = new Imagick();
$mask->newImage($width, $height, new ImagickPixel('none'));
$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_DSTOUT, 0, 0,
    Imagick::CHANNEL_ALPHA);

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

Got black inside yellow, not transparent in yellow


回答1:


You need to make a black and white mask image the size of your input (white where you want it to be opaque and black where you want it to be transparent). Then use the equivalent of -compose copyopacity -composite to put the mask into the alpha channel of the image. Sorry, I do not code Imagick.

Here is an example using ImageMagick command line syntax:

Input:

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

You can see it is transparent by compositing it over another image (in this case a checkerboard).

convert ( -size 640x480 pattern:checkerboard ) result.png -compose over -composite result2.jpg




回答2:


Do you try \Imagick::COMPOSITE_COPYOPACITY ?

Because that's probably the right one.



来源:https://stackoverflow.com/questions/46970937/how-to-make-specified-area-of-an-image-transparent-with-imagick

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!