我發現 Imagick::clipPathImage 和 Imagic::clipImage 的運作方式與我預期的不同。我以為它們只會裁剪路徑,然後丟棄額外的資料,這樣就完成了。但事實並非如此。
以下是我如何使用裁剪路徑的方式
<?php
$img = new Imagick("/Path/To/Test/Image.psd");
$geometry = $img->getImageGeometry();
$img->clipPathImage("#1", false);
$draw = new ImagickDraw();
$draw->setFillColor("#000000");
$draw->color(0,0, imagick::PAINT_RESET);
$img->drawImage($draw);
$composite = new Imagick($path);
$composite->newImage( $geometry['width'], $geometry['height'], new ImagickPixel("white"), 'png');
$composite->compositeImage($img, imagick::COMPOSITE_COPY, 0, 0);
?>
然後對產生的影像進行任何大小調整或建立縮圖,都會忽略先前所有的指令,所以我「儲存」它並從新的 Imagick 物件開始
<?php
$clipped = new Imagick();
$clipped->readImageBlob($composite->getImageBlob());
?>
我確定有更簡單的方法,但我花了很長時間才弄對,而且還有一些障礙需要克服,所以我希望它可以幫助正在摸索的人。
這相當於所有 convert 的操作
$ convert Test.psd -fill white -colorspace rgb -draw "color 0 0 reset" -clip -colorspace rgb -draw "Image Copy 0,0 0,0 'Test.psd'" OutputFile.png