Transparent to white in Imagick for PHP

后端 未结 10 1649
暗喜
暗喜 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:27

    I had a situation where I was trying to replace transparent background with white (but keep as png). Tried several different methods (including setImageAlphaChannel with setImageBackgroundColor). Combining OP's use of compositeImage I came up with this (hopefully helpful to someone else):

    $pic = new Imagick($filelocation); //specify file name
    $pic->setResourceLimit(6, 1);
    if ($pic->getImageAlphaChannel()) {
        $white = new Imagick();
        $white->newImage($pic->getImageWidth(), $pic->getImageHeight(), "white");
        $white->compositeImage($pic, Imagick::COMPOSITE_OVER, 0, 0);
        $pic = clone $white;
        $white->destroy();
        $pic->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);
    }
    //do more things with $pic
    

提交回复
热议问题