Make part of an image transparent with IMagick/ImageMagick

佐手、 提交于 2019-12-23 02:55:08

问题


I wish to make part (or in fact, several parts) of an image transparent using IMagick, such that I can use it as a mask over a different image. I can't figure out any way of doing this in an simple fashion.

So say my starting image is represented as below, where X is any color:

XXXXXXXXXXXXX
XXXXXXXXXXXXX
XXXXXXXXXXXXX
XXXXXXXXXXXXX
XXXXXXXXXXXXX

Then I want to be able to make certain rectangular regions transparent (so it ends up a bit like a punch-card):

XXXXXXXXXXXXX
X  XXXXXXXXXX
X  XXXX  XXXX
XXXXXXX  XXXX
XXXXXXXXXXXXX

Does anyone know of a good way of doing this? Thanks.


回答1:


Figured it out.

//Open your image and get its dimensions
$image = new Imagick('image.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('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( 10,10,100,100 );
$mask->drawImage( $draw );

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


来源:https://stackoverflow.com/questions/20975894/make-part-of-an-image-transparent-with-imagick-imagemagick

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