PHP将png透明背景图片转换为白色背景

发布日期: 2021-07-01 10:41:50 作者: Stephen 评论: 4

前一篇文章中,刚介绍了如何读取PDF文件并转换为png图片,最终图片能正常生成,但遇到了一个问题,生成的图片背景是透明的,那么如何将透明的图片转换为白色背景呢?

找了很多 Imagick 提供的方法都没有成功,包括 setBackgroundImage()setImageBackgroundImage()mergeImageLayers(\Imagick::LAYERMETHOD_FLATTEN) 等等,生成为 jpg 图片背景是黑色的,所以最终我放弃了使用 Imagick 库的方法

解决方法

// 由文件或 URL 创建一个新图象
$image = imagecreatefrompng($file);

// 图片尺寸
$imageWidth = imagesx($image);
$imageHeight = imagesy($image);

// 创建真彩图像资源
$newImage = imagecreatetruecolor($imageWidth, $imageHeight);

// bool imagefilledrectangle ( resource $image , int $x1 , int $y1 , int $x2 , int $y2 , int $color )
// 在 image 图像中画一个用 color 颜色填充了的矩形,其左上角坐标为 x1,y1,右下角坐标为 x2,y2。0, 0 是图像的最左上角。
imagefilledrectangle(
    $newImage, 
    0, 
    0, 
    $imageWidth, 
    $imageHeight, 
    imagecolorallocate($newImage, 255, 255, 255)
);

// 重采样拷贝部分图像并调整大小
imagecopyresampled($newImage, $image, 0, 0, 0, 0, $imageWidth, $imageHeight, $imageWidth, $imageHeight);

// 保存并覆盖图片
imagepng($newImage, $file);

虽然问题解决了,但我不认为这是一个很好的解决办法,如果有更好的方案,还请不吝赐教。

如果能在pdf转png时实现,就更完美了

1111 2年前
非常感谢分享!
闲情计事 2年前
赞一个,支持一下
博主 2年前
@ 闲情计事 感谢您的支持,祝好!
北京艺术** 2年前
感谢分享 赞一个