How to make specified area of an image transparent

2019-08-23 02:28发布

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

result image

2条回答
虎瘦雄心在
2楼-- · 2019-08-23 02:46

Do you try \Imagick::COMPOSITE_COPYOPACITY ?

Because that's probably the right one.

查看更多
戒情不戒烟
3楼-- · 2019-08-23 02:49

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:

enter image description here

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

enter image description here

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

enter image description here

查看更多
登录 后发表回答