Discover & Rate New Music Check out ChartVote. Promote the music you like.


PHP Crop Image

This function will crop an image to the specified width and height without distorting it and in most cases without adding black regions to the image. This function is great for profile photos where the image needs to fit a certain area, but the images being uploaded are of all sizes.

Example
cropexample.jpg

Code

PHP:
  1. cropImage(225, 165, '/path/to/source/image.jpg', 'jpg', '/path/to/dest/image.jpg');
  2.  
  3. function cropImage($nw, $nh, $source, $stype, $dest) {
  4.  
  5.     $size = getimagesize($source);
  6.     $w = $size[0];
  7.     $h = $size[1];
  8.  
  9.     switch($stype) {
  10.         case 'gif':
  11.         $simg = imagecreatefromgif($source);
  12.         break;
  13.         case 'jpg':
  14.         $simg = imagecreatefromjpeg($source);
  15.         break;
  16.         case 'png':
  17.         $simg = imagecreatefrompng($source);
  18.         break;
  19.     }
  20.  
  21.     $dimg = imagecreatetruecolor($nw, $nh);
  22.  
  23.     $wm = $w/$nw;
  24.     $hm = $h/$nh;
  25.  
  26.     $h_height = $nh/2;
  27.     $w_height = $nw/2;
  28.  
  29.     if($w> $h) {
  30.  
  31.         $adjusted_width = $w / $hm;
  32.         $half_width = $adjusted_width / 2;
  33.         $int_width = $half_width - $w_height;
  34.  
  35.         imagecopyresampled($dimg,$simg,-$int_width,0,0,0,$adjusted_width,$nh,$w,$h);
  36.  
  37.     } elseif(($w <$h) || ($w == $h)) {
  38.  
  39.         $adjusted_height = $h / $wm;
  40.         $half_height = $adjusted_height / 2;
  41.         $int_height = $half_height - $h_height;
  42.  
  43.         imagecopyresampled($dimg,$simg,0,-$int_height,0,0,$nw,$adjusted_height,$w,$h);
  44.  
  45.     } else {
  46.         imagecopyresampled($dimg,$simg,0,0,0,0,$nw,$nh,$w,$h);
  47.     }
  48.  
  49.     imagejpeg($dimg,$dest,100);
  50. }


72 Comments

  1. kost on December 19th, 2006

    Thanx!
    Works great.

  2. mokinho on December 20th, 2006

    how do you call the function?

  3. Noah Winecoff on December 20th, 2006

    mokinho:

    You can call the function like this:

    PHP:
    1. cropImage(225, 165, '/path/to/source/image.jpg', 'jpg', '/path/to/dest/image.jpg');

    The first 2 fields specify the width and height of the resulting image.

    This example is given in the post.

  4. mokinho on December 21st, 2006

    K... *sigh* =} - I finally understand how functions are built and called... thank you for that piece of the image.

    Next question....If you don't mind=)??

    calling the path to the image is easy for me if it isn't pathed by a php script but my images are pathed using a php script. So I put in my php script where you show to put the image path, but its not returning my picture. Here is my code...

    ', 'jpg', '')" id="result_pic" alt="No picture available to display">

    Am I missing something here?

  5. Noah Winecoff on December 21st, 2006

    mokinho,

    Replied to you VIA email.

  6. Seiji on January 3rd, 2007

    Hi!
    Thx for posting this! Works fine ;]

  7. Quent on January 8th, 2007

    I am having trouble with the function not cropping the image but instead squishing it to fit inside the width and height I have set (in this case I wanted a 100x100 thumbnail). Is there something I am missing that's causing it to do this?

    I can provide more info on how I am using the function if needed. I am trying to keep the question simple.

    Thanks in advance!

  8. Moses on February 12th, 2007

    I'm having the same issue as Quent, it's just scaling the picture instead of cropping it, but apart from that it works great. Thankyou.

  9. Pac on March 8th, 2007

    This is perfect. So simple and so effective. Thank you!

  10. Pac on March 9th, 2007

    By the way, to fix the problem that causes the image to be squashed instead of cut, replace this:

    if($w> $h) {

    with this:

    if($wm> $hm) {

    -----------

    And replace this:

    } elseif(($w

  11. Pac on March 9th, 2007

    My last comment was truncated.

    ... and replace this:

    } elseif(($w

  12. robert on March 9th, 2007

    I really dont understand something in the code.

    cropImage(225, 165, '/path/to/source/image.jpg', 'jpg', '/path/to/dest/image.jpg'

    I putted the path source to where the image is but now it shows the dest. I dont know on how to configure this!?

  13. robert on March 9th, 2007

    it keeps saying unable to write!?!

  14. bob on March 10th, 2007

    Actually it does add black regions.

  15. robert on March 10th, 2007

    My fault I got it working. Thanks. Its not bad but it actually does add black regions (depending on the actual size of the images dimensions)

    Its works nicely

  16. mufaddal on March 21st, 2007

    it keeps giving
    Call to undefined function imagecreatetruecolor() in c:\Inetpub\wwwroot\hh_2006\testing\cro.php

    are u adding a class or something

  17. Davide on April 4th, 2007

    Ottimo, grazie!
    D.

  18. Linux Geek on April 11th, 2007

    Good function. It helped me get something done a lot sooner. Thanks.

  19. dambi on April 12th, 2007

    It's really a good script !
    Even if the original image is smaller than the final result... it includes black space automatically....

    It's a famous script :)

    Bravo à la française :)

  20. SLOweather on April 12th, 2007

    After messing with this and sort of getting it to work, it doesn't really seem to do what I would call crop. To me an arbitrary crop function cuts a definable part of an image out into a new image. Here, I don't see how to define what part of the image I want to crop.

    After a little research, I think imagecopy will do the crop that I'm thinking of.

  21. henning on May 6th, 2007

    Hey Noah,
    thank you so much!
    You saved a decent amount of work thanks to your function.

    You so rule man!

    regards
    henning

  22. amin on May 9th, 2007

    Ok. that wonderful function. But when try with jpg image it does not crop. Beside it adds the black region around it. Hope u'll take urgent action to rectify the function

  23. Cherry on May 29th, 2007

    Thank you so much!
    it's wonderful function!

  24. alejo on June 6th, 2007

    hello...wonderful function !!!!
    i have my own function more complex like that
    but only missing if we want upload image from
    input type="file", i add this functionality

    Thanks regard...

  25. Lucas on June 25th, 2007

    I added this so I didnt have to know what the image type was since I call mine from the database.

    Just replace:

    switch($stype) {
    case 'gif':
    $simg = imagecreatefromgif($source);
    break;
    case 'jpg':
    $simg = imagecreatefromjpeg($source);
    break;
    case 'png':
    $simg = imagecreatefrompng($source);
    break;
    }

    with this:

    switch ($size[2]) {
    case 1: $simg = imagecreatefromgif($source); break;
    case 2: $simg = imagecreatefromjpeg($source); break;
    case 3: $simg = imagecreatefrompng($source); break;
    default: trigger_error('This is not an allowed image type.', E_USER_WARNING); break;
    }

    Good script thanks!

  26. Tina on July 8th, 2007

    Hiya, I am confused by the path to dest part of the function call. The path to source is where the image is stored I am guessing? I want to display the image on the page I call the function so what do I need for the destination? Thanx

  27. wickedmind on July 17th, 2007

    Hello,
    I tried your script when inserting it into an upload class it works fine with 1 upload but multiple upload i get following error:
    Fatal error: Cannot redeclare cropimage() (previously declared in

    Anyone any idea? i guess it could be solved with destroyimage() but than i don't know which image to destroy.

  28. wickedmind on July 17th, 2007

    problem solved Now it doesn recognized the source, the solution for the previous comment btw was to undo the function thinghy

  29. BiLTeC » Blog Ar?ivi » PHP ile resim kesme on July 23rd, 2007

    [...] cropImage( $yeni_genislik, //olu?turulacak resmin geni?li?i, tam say? olmal? 265 gibi $yeni_yukseklik, //olu?turulacak resmin yüksekli?i, tam say? olmal? 165 gibi ‘kaynak resim yolu/resim.jpg’, // kaynak resim ‘jpg’, // resmin tipi .jpg, gif ve ya png ‘olu?turulacak resim yolu/resim.jpg’ // olu?turulacak resim ); Kaynak: http://www.findmotive.com/2006/12/13/php-crop-image/ [...]

  30. Jabari Bell on August 8th, 2007

    Hey I'm having a problem with this code. I have it pulling in a number of jpeg's, but it's cropping only certain ones for some reason, for the others that it doesn't like, it leaves a black box/area instead of the cropped picture.

    Anyone else having any trouble with this?

    Other than that it works perfectly,

    Thanks in advance

  31. mellypops on August 8th, 2007

    Hi, your script is really handy, it integrated perfectly with my existing resizing code. Thanks!

  32. Walter M. on August 12th, 2007

    Hi,

    This script is really handy, but there is a minor problem. Not all image are perfectly proportioned so when you crop some images, it will result in the image being stretched or compressed. I wrote a small function so that it solves this problem.

    function calcWidth($filename,$height)
    {
    $size = getimagesize($filename);
    $aspect_ratio = $size[1]/$size[0];

    return ($size[1]

  33. Sandip Bhoi on August 24th, 2007

    Hi there...
    I am having a different problem, i am fetching the blob image from database and displaying on page with . This works fine for some images and some of the images get cropped in between.

    The image gets truncated... why... please help me..

  34. Sandip Bhoi on August 24th, 2007

    Hi there...
    I am having a different problem, i am fetching the blob image from database and displaying on page with

    CODE:

    .
    This works fine for some images and some of the images get cropped in between.

    The image gets truncated... why... please help me..

  35. Prince on September 4th, 2007

    M getting an error:

    "Fatal error: Call to undefined function imagecreatefromjpeg() in C:\wamp\www\croptest.php on line 24"

    and i have seen in whole code there is no such function defined "imagecreatefromjpeg() ".

    Plz help me out.

  36. brad on September 12th, 2007

    You need to have an up to date version of PHP with image GD....

  37. Manoj on September 13th, 2007

    Very good script.
    Just 2 problems i am facing.
    1) But some images are not cropped. They are just skipped.
    2) Also, instead of black box/area at the borders, can I have it in white color.

    please help me for the above two problems

    Thanks in advance

  38. Draude on September 15th, 2007

    Works fine!!! Thanks for the function!

    BTW is there any way in which i can crop/resize the image starting on top, not on the middle?

  39. Chris on October 1st, 2007

    Wow! I was just about to slave away on a function like this, but you prevented me from re-inventing sliced bread. Thanks much for sharing! :)

  40. arun on October 26th, 2007

    good example this example very easy and understand thank you

  41. romi on October 31st, 2007

    m getting an error:

    Fatal error: Call to undefined function: imagecreatefromjpeg() in D:\romi\cropimg.php on line 28
    tell me what i do.

  42. Eric on November 4th, 2007

    Great stuff, thanks, my personal goal completed for this week.

    However, if you have more comments in the code to explain what each line, or certain block does, would be better for us to understand how it works.

  43. Jeremy on November 7th, 2007

    Wonderful script. Well done. Easy to use and customize.

  44. Grant Harrison on December 3rd, 2007

    Can anyone help - I'm using a php script that calls images from a db with the following script. These images are external URL links and I'm trying to modify Noah's script to work with the code below? Any help would be appreciated...

    ";
    if(($tinfo[logo]) && ($tinfo[logo]!="http://")){
    $out[body]=$out[body]."";
    }else{

    $out[body]=$out[body]."";
    }

    $out[body]=$out[body]."

  45. Grant Harrison on December 3rd, 2007

    Sorry forget it - may as well just use div tags to force the issue and hide the rest of the image...

  46. lakshmi on December 20th, 2007

    where are thses functions imagecreatetruecolor() and imagecopyresampled() please help me

  47. Nguyen Nhu Tuan on December 23rd, 2007

    I'm have problem, when Image_width > Image_height, cropImage function work not good. Image display with Black backgroup !!! :(

  48. Nguyen Nhu Tuan on December 23rd, 2007

    Sumary my problem:
    If i have a source image (size: axb). i want crop new image (size:a1xb1)

    The case a>b:
    if a1>b1, function work false
    if a1<b1, function work true

    The case ab1, function work true
    if a1b1 and a1<b1

  49. björn on January 2nd, 2008

    hey noah, nice script. works very well! cheers, björn

  50. Prib on January 3rd, 2008

    My problem:
    the image resized :(
    cropped in not actual size.

  51. links for 2008-01-15 at kobak pont org on January 15th, 2008

    [...] PHP Crop Image - Find Motive php kep crop (tags: php crop image images tutorial code photo script programming) [...]

  52. links for 2008-01-15 « kobak del.icio.us könyvjelzÅ‘i on January 15th, 2008

    [...] PHP Crop Image - Find Motive php kep crop (tags: php crop image images tutorial code photo script programming) Posted by kobak Filed in del.icio.us [...]

  53. Onno van Braam on January 24th, 2008

    You're a hero, love the script: small and easy to use, just what I needed!

  54. Onno van Braam on January 27th, 2008

    On second thought: it doesn't do exactly what I want when the image is not in the right proportion: I get additional 'empty space' next to the thumbnails I create.
    I think that is because you check whether the image is more square or not square if($w> $h), but that doesn't make sense when you want the resulting thumbnail to not be square, since then you need to compare the ratio's.

    That's what I did here, in a rewritten script (from scratch) for the cropImage function (remove the file type, and inserted a simple check which makes things easier, but perhaps less robust):

    = $fOrigRatio) {
    $fHalfDifferenceInHeight = ((($iNewWidth / $fOrigRatio) - $iNewHeight) / 2) ;
    imagecopyresampled($mDestinationImage, $mSourceImage, 0, -$fHalfDifferenceInHeight, 0, 0, $iNewWidth, ($iNewWidth / $fOrigRatio), $iOrigWidth, $iOrigHeight) ;
    }
    // The new crop is more standing uppish than the original
    else {
    $fHalfDifferenceInWidth = ((($iNewHeight * $fOrigRatio) - $iNewWidth) / 2) ;
    imagecopyresampled($mDestinationImage, $mSourceImage, -$fHalfDifferenceInWidth, 0, 0, 0, ($iNewHeight * $fOrigRatio), $iNewHeight, $iOrigWidth, $iOrigHeight) ;
    }

    imagejpeg($mDestinationImage, $sDest, 90) ;
    }

    cropImage(160, 120, './Stuff/Marlon-onthewall-004.jpg', './Stuff/Marlon-onthewall-004-cropped.jpg') ;
    cropImage(160, 120, './Stuff/Fiat Coupe.jpg', './Stuff/Fiat Coupe-cropped.jpg') ;

    ?>

  55. Bangiiz on January 29th, 2008

    Thanks alot sir

  56. indu on February 20th, 2008

    i dont know how to use tat, can anyone explain that clearly

  57. Tarubs on February 24th, 2008

    Still not working on my server...

  58. randy on February 26th, 2008

    Thanks bro! Works money!

  59. Peter on February 28th, 2008

    Thanks, saves me a lot of time! Works perfect!

    Greatings from Holland

  60. nD on March 13th, 2008

    I tried, but it return nothing. I chk the cropped thumbnail folder, it does created but it wasnt show in the page.

  61. shady on March 24th, 2008

    great script mate! just a problem though, which i see is not only mine....why do i get that black background at the left and right of the thumb?

  62. mxb on March 25th, 2008

    Hi,
    Nice function.. thanks. But there is something(a feature) that can be added to this function, which is.. how/from where the image should start to crop... like.. left, center, right... and then top,middle,bottom.. :)

  63. Rafael on March 26th, 2008

    Any suggestions on how to make sure it's handling a proper image? For example, what if I send up a BMP pic with a wrong extension (jpg for example)? At what point does the script halt and what I do to return a user-friendly message?

  64. Travis on April 4th, 2008

    usage

    PHP:

    crop.php

    PHP:

  65. Lizzy on May 29th, 2008

    Hey, thanks for this script, it works perfect as long as i don't put a variable in the imagename. Actually that is what i have to... it doesn't read the variable well...
    I still get an error:

    Warning: getimagesize(../friends/foto/$name.jpg) [function.getimagesize]: failed to open stream: No such file or directory in...

    Of course,there is no image "$name.jpg"...

    I guess I'm blind at this point, any idea..?

  66. Patrick on June 2nd, 2008

    Hi, I seem to be getting a black square, the same dimensions as I have told it to crop.. any ideas why this could be?

    Great tutorial though :)

  67. geo on June 12th, 2008

    It works just great!
    but there is a small problem - the image is cut vertically at same distance from top & bottom which doesn't sounds good - the most important pic info is always the top part. so any ideas how can i make it cut the image from top to bottom, and not on the center of the image?

  68. Clinton Skakun on June 12th, 2008

    Looks great, I can't even understand the code at first, but it works so sweet:)

    I just have one suggestion

    jpg is also jpeg, since some images are named xxxx.jpeg, and can also upper case...so here:)

    switch(strtolower($type))
    {
    case 'gif':
    $simg = imagecreatefromgif($source_image);
    break;
    case 'jpg':
    case 'jpeg':
    $simg = imagecreatefromjpeg($source_image);
    break;
    case 'png':
    $simg = imagecreatefrompng($source_image);
    break;
    }

    hope I was of some help, btw any place I use this code I'll have your name and a link to this article.
    Thanks

  69. Baudry on June 15th, 2008

    Today i would like to make a little research'motor by pictures with this

    <?php
    $nb_lignes=4;
    $nb_colonnes=6;

    for($i=1;$i<=$nb_lignes;$i=$i+1){

    echo "";

    for($j=1;$j<=$nb_colonnes;$j=$j+1){
    echo ''.$img.'/n';
    }

    echo "\n";

    }
    ?>

    I would like to display pictures by 120 pixels for each. But my idea is displaying pictures from post or page and if you click on one you can see the post or page when picture is. Maybe Everyone who see it think it 's interesting and add fonctions at my short code.

  70. Baudry on June 15th, 2008

    I have another idea to use your crop script with this:

    http://photomatt.net
    Inspired by Dan Benjamin > http://hiveware.com/imagerotator.php
    Latest version always at:
    http://photomatt.net/scripts/randomimage
    */// Make this the relative path to the images, like "../img" or "random/images/".
    // If the images are in the same directory, leave it blank.
    $folder = '';

    // Space seperated list of extensions, you probably won't have to change this.
    $exts = 'jpg jpeg png gif';

    $files = array(); $i = -1; // Initialize some variables
    if ('' == $folder) $folder = './';

    $handle = opendir($folder);
    $exts = explode(' ', $exts);
    while (false !== ($file = readdir($handle))) {
    foreach($exts as $ext) { // for each extension check the extension
    if (preg_match('/\.'.$ext.'$/i', $file, $test)) { // faster than ereg, case insensitive
    $files[] = $file; // it’s good
    ++$i;
    }
    }
    }
    closedir($handle); // We’re not using it anymore
    mt_srand((double)microtime()*1000000); // seed for PHP but I don't kow to make a good script with crop fonction and my research pictures script : <?php
    $nb_lignes=4;
    $nb_colonnes=6;

    for($i=1;$i<=$nb_lignes;$i=$i+1){

    echo "";

    for($j=1;$j

    I would like to display pictures by 120 pixels for each. But my idea is displaying pictures from post or page and if you click on one you can see the post or page when picture is. Maybe Everyone who see it think it 's interesting and add fonctions at my short code.

  71. Kestas on June 17th, 2008

    It's don't work for me. This function resizes image, but not crop.

  72. web design on June 19th, 2008

    sweet function did exactly what i could have hoped straight away. your a php ninja

Leave a Reply

RSS Feed



Recommended Sites