Cropping image in PHP

30,085

Solution 1

You could use imagecopy to crop a required part of an image. The command goes like this:

imagecopy  ( 
    resource $dst_im - the image object ,
    resource $src_im - destination image ,
    int $dst_x - x coordinate in the destination image (use 0) , 
    int $dst_y - y coordinate in the destination image (use 0) , 
    int $src_x - x coordinate in the source image you want to crop , 
    int $src_y - y coordinate in the source image you want to crop , 
    int $src_w - crop width ,
    int $src_h - crop height 
)

Code from PHP.net - a 80x40 px image is cropped from a source image

<?php
// Create image instances
$src = imagecreatefromgif('php.gif');
$dest = imagecreatetruecolor(80, 40);

// Copy
imagecopy($dest, $src, 0, 0, 20, 13, 80, 40);

// Output and free from memory
header('Content-Type: image/gif');
imagegif($dest);

imagedestroy($dest);
imagedestroy($src);
?>

Solution 2

This function will crop image maintaining image aspect ratio :)

 function resize_image_crop($image, $width, $height)
     {

        $w = @imagesx($image); //current width

        $h = @imagesy($image); //current height
        if ((!$w) || (!$h)) { $GLOBALS['errors'][] = 'Image couldn\'t be resized because it wasn\'t a valid image.'; return false; }
        if (($w == $width) && ($h == $height)) { return $image; }  //no resizing needed
        $ratio = $width / $w;       //try max width first...
        $new_w = $width;
        $new_h = $h * $ratio;    
        if ($new_h < $height) {  //if that created an image smaller than what we wanted, try the other way
            $ratio = $height / $h;
            $new_h = $height;
            $new_w = $w * $ratio;
        }
        $image2 = imagecreatetruecolor ($new_w, $new_h);
        imagecopyresampled($image2,$image, 0, 0, 0, 0, $new_w, $new_h, $w, $h);    
        if (($new_h != $height) || ($new_w != $width)) {    //check to see if cropping needs to happen
            $image3 = imagecreatetruecolor ($width, $height);
            if ($new_h > $height) { //crop vertically
                $extra = $new_h - $height;
                $x = 0; //source x
                $y = round($extra / 2); //source y
                imagecopyresampled($image3,$image2, 0, 0, $x, $y, $width, $height, $width, $height);
            } else {
                $extra = $new_w - $width;
                $x = round($extra / 2); //source x
                $y = 0; //source y
                imagecopyresampled($image3,$image2, 0, 0, $x, $y, $width, $height, $width, $height);
            }
            imagedestroy($image2);
            return $image3;
        } else {
            return $image2;
        }
    }

Solution 3

To crop an image using GD you need to use a combination of GD methods, and if you look at "Example #1" on PHP's documentation of the imagecopyresampled method, it shows you how to crop and output an image, you would just need to add some code to that to capture and write the output to a file...

http://us2.php.net/manual/en/function.imagecopyresampled.php

There are also other options, including Image Magick which, if installed on your server, can be accessed directly using PHP's exec method (or similar) or you can install the PHP Imagick extension, which yields higher quality images and, in my opinion, is a little more intuitive and flexible to work with.

Finally, I've used the open source PHPThumb class library, which has a pretty simple interface and can work with multiple options depending on what's on your server, including ImageMagick and GD.

Share:
30,085
user244228
Author by

user244228

Updated on December 03, 2020

Comments

  • user244228
    user244228 over 3 years

    I'd like crop an image in PHP and save the file. I know your supposed to use the GD library but i'm not sure how. Any ideas?

    Thanks

  • AlexV
    AlexV over 14 years
    shiftingpixel.com seems down for the moment try the link later :)
  • AlexV
    AlexV over 14 years
    shiftingpixel.com is back now :)
  • bayblade567
    bayblade567 almost 9 years
    Wont this method add black background to PNG images? I mean over the transparent background?
  • shrmn
    shrmn over 8 years
    It might be helpful to users if you add comments to your code to explain what key parts do. This would help them better understand and apply your code
  • Exit
    Exit over 7 years
    Shouldn't need to do multiple imagecopyresampled calls, it can all be done on one call if the offset is calculated in to the $width and $height. Also, might be preferable to always force the resize to ensure that the image is saved in a new format stripped of additional garbage and headers and forced to a specific quality.
  • totymedli
    totymedli about 6 years
    You could also use imagecrop.