Convert PNG to JPG and set transparent background to white with ImageMagick and PHP

前端 未结 2 984
盖世英雄少女心
盖世英雄少女心 2021-02-03 23:48

How can I use ImageMagick (with the php extension) to set the transparent background to white when converting an image from PNG to JPEG?

2条回答
  •  深忆病人
    2021-02-03 23:53

    At time of writing, you have not specified which extension you are using, but if you were using the commandline, the command would be:

    convert image.png -background white -flatten -alpha off image.jpg
    

    More information can be found on the Masking Usage documentation.

    Using IMagick for instance, I think you could do this as follows:

    (totally untested, never used IMagick and don't have it installed to test)

    $image = new IMagick('image.png');
    
    $flattened = new IMagick();
    $flattened->newImage($image->getImageWidth(), $image->getImageHeight(), new ImagickPixel("white"));
    
    $flattened->compositeImage($image, imagick::COMPOSITE_OVER, 0, 0);
    
    $flattened->setImageFormat("jpg");
    $flattened->writeImage('image.jpg');
    
    $image->clear();
    $image->destroy();
    $flattened->clear();
    $flattened->destroy();
    

提交回复
热议问题