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

Code
PHP:
-
cropImage(225, 165, '/path/to/source/image.jpg', 'jpg', '/path/to/dest/image.jpg');
-
-
function cropImage($nw, $nh, $source, $stype, $dest) {
-
-
$w = $size[0];
-
$h = $size[1];
-
-
switch($stype) {
-
case 'gif':
-
$simg = imagecreatefromgif($source);
-
break;
-
case 'jpg':
-
$simg = imagecreatefromjpeg($source);
-
break;
-
case 'png':
-
$simg = imagecreatefrompng($source);
-
break;
-
}
-
-
$dimg = imagecreatetruecolor($nw, $nh);
-
-
$wm = $w/$nw;
-
$hm = $h/$nh;
-
-
$h_height = $nh/2;
-
$w_height = $nw/2;
-
-
if($w> $h) {
-
-
$adjusted_width = $w / $hm;
-
$half_width = $adjusted_width / 2;
-
$int_width = $half_width - $w_height;
-
-
imagecopyresampled($dimg,$simg,-$int_width,0,0,0,$adjusted_width,$nh,$w,$h);
-
-
} elseif(($w <$h) || ($w == $h)) {
-
-
$adjusted_height = $h / $wm;
-
$half_height = $adjusted_height / 2;
-
$int_height = $half_height - $h_height;
-
-
imagecopyresampled($dimg,$simg,0,-$int_height,0,0,$nw,$adjusted_height,$w,$h);
-
-
} else {
-
imagecopyresampled($dimg,$simg,0,0,0,0,$nw,$nh,$w,$h);
-
}
-
-
imagejpeg($dimg,$dest,100);
-
}

My name is Noah Everett. I live in Tulsa, OK. I started 
Thanx!
Works great.
how do you call the function?
mokinho:
You can call the function like this:
The first 2 fields specify the width and height of the resulting image.
This example is given in the post.
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?
mokinho,
Replied to you VIA email.
Hi!
Thx for posting this! Works fine ;]
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!
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.
This is perfect. So simple and so effective. Thank you!
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
My last comment was truncated.
... and replace this:
} elseif(($w
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!?
it keeps saying unable to write!?!
Actually it does add black regions.
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
it keeps giving
Call to undefined function imagecreatetruecolor() in c:\Inetpub\wwwroot\hh_2006\testing\cro.php
are u adding a class or something
Ottimo, grazie!
D.
Good function. It helped me get something done a lot sooner. Thanks.
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
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.
Hey Noah,
thank you so much!
You saved a decent amount of work thanks to your function.
You so rule man!
regards
henning
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
Thank you so much!
it's wonderful function!
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...
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!
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
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.
problem solved Now it doesn recognized the source, the solution for the previous comment btw was to undo the function thinghy
[...] 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/ [...]
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
Hi, your script is really handy, it integrated perfectly with my existing resizing code. Thanks!
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]
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..
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..
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.
You need to have an up to date version of PHP with image GD....
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
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?
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!
good example this example very easy and understand thank you
m getting an error:
Fatal error: Call to undefined function: imagecreatefromjpeg() in D:\romi\cropimg.php on line 28
tell me what i do.
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.
Wonderful script. Well done. Easy to use and customize.
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]."
Sorry forget it - may as well just use div tags to force the issue and hide the rest of the image...
where are thses functions imagecreatetruecolor() and imagecopyresampled() please help me
I'm have problem, when Image_width > Image_height, cropImage function work not good. Image display with Black backgroup !!!
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
hey noah, nice script. works very well! cheers, björn
My problem:
the image resized
cropped in not actual size.
[...] PHP Crop Image - Find Motive php kep crop (tags: php crop image images tutorial code photo script programming) [...]
[...] 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 [...]
You're a hero, love the script: small and easy to use, just what I needed!
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') ;
?>
Thanks alot sir
i dont know how to use tat, can anyone explain that clearly
Still not working on my server...
Thanks bro! Works money!
Thanks, saves me a lot of time! Works perfect!
Greatings from Holland
I tried, but it return nothing. I chk the cropped thumbnail folder, it does created but it wasnt show in the page.
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?
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..
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?
usage
crop.php
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..?
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
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?
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
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.
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.
It's don't work for me. This function resizes image, but not crop.
sweet function did exactly what i could have hoped straight away. your a php ninja