Remove transparent background from uploaded PNG files

66 Views Asked by At

We want all the uploaded images to start from the same position so we would like to crop/remove the transparent backgrounds from the images. Here are 2 examples of images uploaded:

Image 1

Image 2

As you can see the "A" letter is in the middle with a transparent background while the "F" letter starts from the left with a transparent background.

Here is the code to remove the transparent background while uploading the images:

$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);
}

The script saves images like this:

image.png

I tried to use the following functions before cropping:

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

But didn't work.

1

There are 1 best solutions below

0
user On

This is a known GD bug for images with alpha channel, afaik. If you don't mind to replace the transparent background with a white one, try this:

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);
}