PHP convert psd to jpg, selecting image layers

2019-04-11 05:41发布

问题:

I want to be able to select which layers from a .PSD image are merged into the final .JPG output image.

I can merge all of the layers in the image with:

$im = new Imagick('test.psd');
$im->flattenImages();
$im->setImageFormat('jpg');
$im->writeImage('test.jpg');

However the .psd contains about 10 layers and I want to be able to specify which specific layers should be merged together, to produce the final image.

For example I want to merge only layer numbers 3, 5 and 10 or the layers with names "RED", "GREEN", "BLUE"

回答1:

Although hsz's answer is correct, and is the best way when the images are very large, it does require you to know ahead of time which layers you want to merge.

You can do the same thing more programmatically by using setIteratorIndex to access the individual layers and adding them to an output image.

    $imagick = new \Imagick(realpath("../images/LayerTest.psd"));

    $output = new \Imagick();
    $imagick->setIteratorIndex(1);
    $output->addImage($imagick->getimage());

    $imagick->setIteratorIndex(2);
    $output->addImage($imagick->getimage());

    $merged = @$output->flattenimages();
    $merged->setImageFormat('jpg');
    $merged->writeImage('test.jpg');


回答2:

You can access third layer with

test.psd[3]

Just try with:

$im = new Imagick(array('test.psd[3]', 'test.psd[5]', 'test.psd[10]'));