Question

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

Was it helpful?

Solution

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

OTHER TIPS

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

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.

I use this script in some projects and it's pretty easy to use: http://shiftingpixel.com/2008/03/03/smart-image-resizer/

The script requires PHP 5.1.0 (which is out since 2005-11-24 - time to upgrade if not yet at this version) and GD (which is rarely missing from good Web hosts).

Here is an example of it's use in your HTML:

<img src="/image.php/coffee-bean.jpg?width=200&amp;height=200&amp;image=/wp-content/uploads/2008/03/coffee-bean.jpg" alt="Coffee Bean" />

I just created this function and it works for my needs, creating a centered and cropped thumbnail image. It is streamlined and doesn't require multiple imagecopy calls like shown in webGautam's answer.

Provide the image path, the final width and height, and optionally the quality of the image. I made this for creating thumbnails, so all images are saved as JPGs, you can edit it to accommodate other image types if you require them. The main point here is the math and method of using imagecopyresampled to produce a thumbnail. Images are saved using the same name, plus the image size.

function resize_crop_image($image_path, $end_width, $end_height, $quality = '') {
 if ($end_width < 1) $end_width = 100;
 if ($end_height < 1) $end_height = 100;
 if ($quality < 1 || $quality > 100) $quality = 60;

 $image = false;
 $dot = strrpos($image_path,'.');
 $file = substr($image_path,0,$dot).'-'.$end_width.'x'.$end_height.'.jpg';
 $ext = substr($image_path,$dot+1);

 if ($ext == 'jpg' || $ext == 'jpeg') $image = @imagecreatefromjpeg($image_path);
 elseif($ext == 'gif') $image = @imagecreatefromgif($image_path);
 elseif($ext == 'png') $image = @imagecreatefrompng($image_path);

 if ($image) {
  $width = imagesx($image);
  $height = imagesy($image);
  $scale = max($end_width/$width, $end_height/$height);
  $new_width = floor($scale*$width);
  $new_height = floor($scale*$height);
  $x = ($new_width != $end_width ? ($width - $end_width) / 2 : 0);
  $y = ($new_height != $end_height ? ($height - $end_height) / 2 : 0);
  $new_image = @imagecreatetruecolor($new_width, $new_height);

  imagecopyresampled($new_image,$image,0,0,$x,$y,$new_width,$new_height,$width - $x,$height - $y);
  imagedestroy($image);
  imagejpeg($new_image,$file,$quality);
  imagedestroy($new_image);

  return $file;
 }
 return false;
}

You can use below method to crop image,

/*parameters are 
    $image =source image name
    $width = target width
    $height = height of image
    $scale = scale of image*/
    function resizeImage($image,$width,$height,$scale) {
        //generate new image height and width of source image
        $newImageWidth = ceil($width * $scale);
        $newImageHeight = ceil($height * $scale);
        //Create a new true color image
        $newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
        //Create a new image from file 
        $source = imagecreatefromjpeg($image);
        //Copy and resize part of an image with resampling
        imagecopyresampled($newImage,$source,0,0,0,0,$newImageWidth,$newImageHeight,$width,$height);
        //Output image to file
        imagejpeg($newImage,$image,90);
        //set rights on image file
        chmod($image, 0777);
        //return crop image
        return $image;
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top