从上传的 PNG 文件中删除透明背景

Remove transparent background from uploaded PNG files

提问人:john 提问时间:10/30/2023 更新时间:10/31/2023 访问量:43

问:

我们希望所有上传的图像都从同一位置开始,因此我们希望从图像中裁剪/删除透明背景。以下是上传的图片的 2 个示例:

Image 1

Image 2

如您所见,“A”字母位于中间,背景透明,而“F”字母从左侧开始,背景透明。

以下是在上传图像时删除透明背景的代码:

$extension = strtolower(pathinfo($_FILES['avatar']['name'])['extension']);
if($extension == 'png'){
    $image = $_FILES['avatar']['tmp_name'];
    $filePath = "images/image.png";
    $im = imagecreatefrompng($image);
    $cropped = imagecropauto($im, IMG_CROP_DEFAULT);
    if ($cropped !== false) {
        imagedestroy($im);
        $im = $cropped;
    }
    imagepng($im, $filePath);
    imagedestroy($im);
}

该脚本保存图像的方式如下:

image.png

在裁剪之前,我尝试使用以下功能:

imagealphablending($im, false);
imagesavealpha($im, true);
$cropped = imagecropauto($im, IMG_CROP_DEFAULT);

但没有用。

PHP GD

评论


答:

1赞 user 10/31/2023 #1

对于具有 alpha 通道 afaik 的图像,这是一个已知的 GD 错误。如果您不介意用白色背景替换透明背景,请尝试以下操作:

function crop($input_file, $output_file) {
    // Get the original image.
    $src = imagecreatefrompng($input_file);

    // Get the width and height.
    $width = imagesx($src);
    $height = imagesy($src);

    // Create image with a white background, 
    // the same size as the original.
    $bg_white = imagecreatetruecolor($width, $height);
    $white = imagecolorallocate($bg_white, 255, 255, 255);
    imagefill($bg_white, 0, 0, $white);

    // Merge the two images.
    imagecopyresampled(
        $bg_white, $src,
        0, 0, 0, 0,
        $width, $height,
        $width, $height);

    // Crop new image w/ white background
    $cropped = imagecropauto($bg_white, IMG_CROP_WHITE);
    if ($cropped !== false) {
        imagedestroy($bg_white);
        $bg_white = $cropped;
    }

    // Save the finished image.
    imagepng($bg_white, $output_file, 0);
}