douzhan1868 2017-10-27 08:43
浏览 582
已采纳

如何使用Imagick使图像的指定区域透明?

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条回答 默认 最新

  • douzhou7656 2017-10-27 17:19
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?