Transparent to white in Imagick for PHP

后端 未结 10 1665
暗喜
暗喜 2020-12-16 11:58

I have a png image with a transparent background and I want to convert it to a jpg image with a white background.

The code is basically this:

$image          


        
10条回答
  •  心在旅途
    2020-12-16 12:35

    flattenImages() actually works.

    But keep in mind that it doesn't modify the given \Imagick() object but returns a new one:

    $image = new \Imagick('transparent.png');
    
    // Need to use the result of $image->flattenImages() here!
    $image = $image->flattenImages();
    $image->writeImage('opaque.jpg');
    

    flattenImages() defaults to the background color white. If you want to use another background color you have to set it before loading the image:

    $image = new \Imagick();
    
    // Needs to be called before the image is loaded!
    $image->setbackgroundcolor('green');
    $image->readimage('transparent.png');
    
    $image = $image->flattenImages();
    $image->writeImage('opaque.jpg');
    

    In general the Imagick API is very sensible when it comes to the order of function calls (just like convert and its parameters on the command line) so always check if your order is correct.

    Good luck!

    Edit April 2016:

    $image->flattenImages() was deprecated and should be replaced by:

    $image->mergeImageLayers(\Imagick::LAYERMETHOD_FLATTEN)
    

    It's hard to find exact informations about this, but it seems that this applies to PHP >= 5.6.

    Thanks to vee for the tip!

提交回复
热议问题