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

问题描述 投票:0回答:1

我们希望所有上传的图像都从同一位置开始,因此我们希望从图像中裁剪/删除透明背景。以下是上传图片的 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);
}

脚本保存图像如下:

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

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

但没有成功。

php gd
1个回答
0
投票

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

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);
}
© www.soinside.com 2019 - 2024. All rights reserved.