Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / PHP

Cropping of Image from Center Co-ordinates

3.67/5 (3 votes)
13 Jan 2013CPOL1 min read 16.5K   720  
Helpful to develop photo gallery

Introduction

The practical use of this submission is very extensive, in such types of PHP developments where the developers are working with images, especially thumbnails for developing photo galleries. The original images have various diversities with their dimensions, but thumbnails must be identical by their dimensions. Sometimes, it's very difficult for developers to represent the actual view of original photographs after cropping by their thumbnails. To overcome this problem, here a class has been developed which makes thumbnails from a prominent part of the image - the Center.

Source Files

  1. index.php – the landing page, where I keep the HTML form
  2. class.crop_center.php – the file containing class
  3. tulips.jpg – an image for example

Description

Here, in index.php page, you'll get a simple form, which demands an image to crop it by center.

Image 1

Now, browse an image for what you have to make a cropped thumbnail.
Image 2

After action taken by submit button, the original image as well as the centered-cropped image have been displayed as follows:
Image 3

Using the Code

On index.php file, you will find that a class has been included as:

PHP
include('class.crop_center.php');
$objZF		=	new CropCenter;

And the object objZF called a function as:

PHP
crop_center(given_file, renamed_file, width_cropped_image, height_cropped_image) 

which takes a total of four parameters - two for images and two for given dimensions for cropped image as output.

PHP
// READ WIDTH & HEIGHT OF ORIGINAL IMAGE
list($current_width, $current_height) = getimagesize($new_name);
			
// CENTER OF GIVEN IMAGE, WHERE WE WILL START THE CROPPING
$left	=	($current_width / 2) - ($crop_width / 2);
$top 	=	($current_height / 2) - ($crop_height / 2);
			
// BUILD AN IMAGE WITH CROPPED PART
$new_canvas = imagecreatetruecolor($crop_width, $crop_height);
$new_image = imagecreatefromjpeg($new_name);
imagecopy($new_canvas, $new_image, 0, 0, $left, $top, $current_width, $current_height);
imagejpeg($new_canvas, $new_name, 100);

Conclusion

I wish this will help the developers developing photo galleries.

History

  • 12th January, 2013: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)