cropping an image script
| From: | Anthony Ritter | Date: | Thu, 13 Mar 2003 16:07:28 +0000 |
| Subject: | cropping an image script | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-139528@lists.php.net to get a copy of this message | ||
In the following php script, the function takes the original file and crops
to the destination file.
I've ran the script using a .png file and a .jpg file.
The .png works fine whereas the .jpeg file returns only part of the image
along with a blue rectangle.
For instance - where the original image is a 200 x 300 jpeg called:
1_data.jpeg
and the destination iamge is 75x75 called:
2_data.jpeg
and starting at the x,y coordinates of 0,0 - the script returns a 75x 75
file but only a sliver of the .jpg image is within the 75x75 blue square.
Any help will be of assistance.
Thank you.
Tony Ritter
........................................................
The following is the php cropping script (with author credit):
<?
//
// image crop fuction ..... Duck@obala.net
// info at http://obala.net/en
//
// Yes the proses could be executed with imagecopyresized build-in function
// but with this function you get the idea of how an image color set is
constructed
//
// $cropX = source starting X
// $cropY = source starting Y
// $cropW = crop weigth
// $cropH = crop heigh
// $source = source filename
// $destination = destination filename
// $type = image type
function
im_crop($cropX,$cropY,$cropH,$cropW,$source,$destination,$type='jpeg') {
// switch known types and open source image
switch ($type) {
case 'wbmp': $sim = ImageCreateFromWBMP($source); break;
case 'gif': $sim = ImageCreateFromGIF($source); break;
case 'png': $sim = ImageCreateFromPNG($source); break;
default: $sim = ImageCreateFromJPEG($source); break;
}
// create the destination image
$dim = imagecreate($cropW, $cropH);
// pass trought pixles of source image
for ( $i=$cropY; $i<($cropY+$cropH); $i++ ) {
for ( $j=$cropX; $j<($cropX+$cropW); $j++ ) {
// get RGB color info about a pixel in the source image
$color = imagecolorsforindex($sim, imagecolorat($sim, $j, $i));
// insert the color in the color index of the new image
$index = ImageColorAllocate($dim, $color['red'],
$color['green'], $color['blue']);
// plots a pixel in the new image with that color
imagesetpixel($dim, $j-$cropX, $i-$cropY, $index);
}
}
// whe dont need the sorce image anymore
imagedestroy($sim);
// switch known types and save
switch ($type) {
case 'wbmp': ImageWBMP($dim, $destination); break;
case 'gif': ImageGIF($dim, $destination); break;
case 'png': ImagePNG($dim, $destination); break;
default: ImageJPEG($dim, $destination); break;
}
// free the used space of the source image
imagedestroy($dim);
}
// example
im_crop(0,0,75,75,'1_data.jpeg','2_data.jpeg','jpeg');
?>