Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

imagecrop() alternative for PHP < 5.5

A simple question motivated by a curiosity, with probably a complex answer: Is it possible to emulate the new PHP 5.5 imagecrop() in earlier versions, like 5.4, by combining other GD functions?

Awn.. But without the imagecrop() black line bug, please. :p

like image 836
Bruno Augusto Avatar asked Nov 03 '14 20:11

Bruno Augusto


People also ask

How to crop an image to a rectangle in PHP?

The imagecrop() function is an inbuilt function in PHP which is used to crop an image to the given rectangle. This function crops an image to the given rectangular area and returns the resulting image.

What is the difference between image and imagecrop ()?

Returns a cropped image object on success or false on failure. If the complete image was cropped, imagecrop () returns false . image expects a GdImage instance now; previously, a resource was expected. On success, this function returns a GDImage instance now; previously, a resource was returned.

What does imagecropauto () return when I crop an image?

As noted in the return value section, imagecropauto () returns false if the whole image was cropped. In this example we have an image object $im which should be automatically cropped only if there is something to crop; otherwise we want to proceed with the original image.

How to automatically crop an image according to the mode?

Automatically crops an image according to the given mode . A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor (). One of the following constants: Same as IMG_CROP_TRANSPARENT. Before PHP 7.4.0, the bundled libgd fell back to IMG_CROP_SIDES, if the image had no transparent color.


1 Answers

This should be a drop-in replacement for imagecrop() (without the bug...):

function mycrop($src, array $rect)
{
    $dest = imagecreatetruecolor($rect['width'], $rect['height']);
    imagecopy(
        $dest,
        $src,
        0,
        0,
        $rect['x'],
        $rect['y'],
        $rect['width'],
        $rect['height']
    );

    return $dest;
}

Usage:

$img = mycrop($img, ['x' => 10, 'y' => 10, 'width' => 100, 'height' => 100]);

Note that the bug is apparently fixed in PHP 5.6.12.

like image 61
timclutton Avatar answered Sep 23 '22 15:09

timclutton