Crop image in PHP.

You can download the uploader.class.php file from this link:
http://www.freelancer-id.com/uploader.class-1.2
This class can:
- Upload images and files.
- Resize images.
- Crop images.

I was looking for a simple way to crop part of an image using PHP code. The idea of this is to create image thumbnail for large images uploaded. These large images could be used for previews, screen shots, wallpapers.. etc.

And because we don’t have an exact ratio between Image width and height, we should crop part of the original image to use it as a thumbnail.

Note: we can find the ratio between width and height and then resize the image. But this won’t work prefect, so we better use cropping to get the size we need.
Also, we can crop part of resized image to use it as a thumbnail.

Let me now explain the code used to crop part of image.


// Receiving image.
$image = $_FILES["image"]["tmp_name"];
// Creating temp image as a source image (original image).
$src = imagecreatefromjpeg($image);

// Create new image with a new width and height.
$dest = imagecreatetruecolor($width, $height);

// Copy new image to memory after cropping.
imagecopy($dest, $src, 0, 0, $left, $top, $width, $height);

$path="images/croppedImage.jpg";
$compress = 60;

// Creating new image cropped image as JPG and save it to $dest
imagejpeg($dest,$path,$compress);

// Freeing up memory.
imagedestroy($dest);
imagedestroy($src);

Hope this will be helpful.

Also, you can download the the latest class from: http://www.freelancer-id.com/upload-crop-resize-in-php

0
0
  

32 Comments to “Crop image in PHP.”

  1. nguyen duc dung 12 July 2009 at 12:22 pm #

    thanks you. Greate.

  2. Sami Mansour 23 November 2009 at 2:16 pm #

    really great, i like it.
    thnx

  3. Somnath 10 December 2009 at 3:52 pm #

    Nice code… thank you.

  4. Gourmet Food 10 March 2010 at 4:12 pm #

    thanks,

  5. Web Design Horsham 31 March 2010 at 7:48 pm #

    Super tutorial thanksand very well written!

  6. semmonecspeluri 29 August 2010 at 4:25 am #

    niceeeee how much ?

  7. Biz Job Finder 8 July 2011 at 1:39 am #

    Nice Code.
    question is this code supported any file format? png gif ?


Leave a Reply