phpimagephp-gd

Crop a png image with PHP, remove empty transparency


I'm currently trying to work with pictures and PHP, thanks to GD functions. Now I would like to modify the size of PNG pictures. Here is an example of a PNG I'd like to resize : enter image description here

The dotted line represent the border of the PNG, the background is transparent, and I only have a star lost on the middle of a large space. I'd like to crop this star, to get a simple square of the star (even if the new background becomes blank, It doesn't matter).

How could I do something like that efficiently ? I thought about doing a loop checking every pixel of the picture.. Trying to find where the image is, to finally crop with a little margin based on the minimum x / maximum X and minimum y / maximum y values, but If I start working with hundreds of pictures, It would be really long.

EDIT :

<?php

$file = "./crop.png";

$ext = pathinfo($file, PATHINFO_EXTENSION);

$image;

switch ($ext){
case 'png':
    $image = imagecreatefrompng($file);
    break;

case 'jpeg':
case 'jpg':
    $image = imagecreatefromjpeg($file);
    break;

case 'gif':
    $image = imagecreatefromgif($file);
    break;
}

$cropped = imagecropauto($image, IMG_CROP_DEFAULT);

    if ($cropped !== false) { // in case a new image resource was returned
        echo "=> Cropping needed\n";
        imagedestroy($image);    // we destroy the original image
        $image = $cropped;       // and assign the cropped image to $im
    }

    imagepng($image, "./cropped.png");
    imagedestroy($image);

Solution

  • If you read and follow the documentation, you'll find a function called imagecropauto which does exactly what you want, it crops the alpha channel of the image.

    Crop an PNG image with alpha channel

    $im = imagecreatefrompng("./star-with-alpha.png");
    $cropped = imagecropauto($im, IMG_CROP_DEFAULT);
    
    if ($cropped !== false) { // in case a new image resource was returned
        imagedestroy($im);    // we destroy the original image
        $im = $cropped;       // and assign the cropped image to $im
    }
    
    imagepng($im, "./star-with-alpha-crop.png");
    imagedestroy($im);
    

    You can try it dirrectly to a php page using this code:

    <body>
    
    <img src="star-with-alpha.png">
    
    <?php 
    
    $im = imagecreatefrompng("./star-with-alpha.png");
    $cropped = imagecropauto($im, IMG_CROP_DEFAULT);
    
    if ($cropped !== false) { // in case a new image resource was returned
        imagedestroy($im);    // we destroy the original image
        $im = $cropped;       // and assign the cropped image to $im
    }
    
    imagepng($im, "./star-with-alpha-crop.png");
    imagedestroy($im);
    
    ?>
    
    <img src="star-with-alpha-crop.png">
    
    </body>
    

    The result

    http://zikro.gr/dbg/php/crop-png/

    Cropped image demo