PHP: Cropping a Rectangle Image to Square using GD
Posted on October 1, 2008, Filled under PHP,
Bookmark it
Hello coders,
This is a PHP Class that crops images (rectangles) to squares using the GD library. First, make sure you have this extension enabled. This can be verified using the following code:
check_gd.php
<?php
if (!extension_loaded('gd')) {
if (!dl('gd.so')) {
exit("The GD extension is not loaded.");
}
}
?>
The class checks if the image is already a square. If it is, it will output a message to the user. If it’s not it will calculate the necessary coordinates and crop it: to left, center or right (default is ‘center’).
crop.image.to.square.class.php
<?php
/*
--------------------------------------------------------------------------------------------
Credits: Bit Repository
Source URL: http://www.bitrepository.com/web-programming/php/crop-rectangle-to-square.html
--------------------------------------------------------------------------------------------
*/
/* Crop Image Class */
class Crop_Image_To_Square {
var $source_image;
var $new_image_name;
var $save_to_folder;
function crop($location = 'center')
{
$info = GetImageSize($this->source_image);
$width = $info[0];
$height = $info[1];
$mime = $info['mime'];
if($width == $height)
{
echo 'The source image is already a square.';
}
else
{
// What sort of image?
$type = substr(strrchr($mime, '/'), 1);
switch ($type)
{
case 'jpeg':
$image_create_func = 'ImageCreateFromJPEG';
$image_save_func = 'ImageJPEG';
$new_image_ext = 'jpg';
break;
case 'png':
$image_create_func = 'ImageCreateFromPNG';
$image_save_func = 'ImagePNG';
$new_image_ext = 'png';
break;
case 'bmp':
$image_create_func = 'ImageCreateFromBMP';
$image_save_func = 'ImageBMP';
$new_image_ext = 'bmp';
break;
case 'gif':
$image_create_func = 'ImageCreateFromGIF';
$image_save_func = 'ImageGIF';
$new_image_ext = 'gif';
break;
case 'vnd.wap.wbmp':
$image_create_func = 'ImageCreateFromWBMP';
$image_save_func = 'ImageWBMP';
$new_image_ext = 'bmp';
break;
case 'xbm':
$image_create_func = 'ImageCreateFromXBM';
$image_save_func = 'ImageXBM';
$new_image_ext = 'xbm';
break;
default:
$image_create_func = 'ImageCreateFromJPEG';
$image_save_func = 'ImageJPEG';
$new_image_ext = 'jpg';
}
// Coordinates calculator
if($width > $height) // Horizontal Rectangle?
{
if($location == 'center')
{
$x_pos = ($width - $height) / 2;
$x_pos = ceil($x_pos);
$y_pos = 0;
}
else if($location == 'left')
{
$x_pos = 0;
$y_pos = 0;
}
else if($location == 'right')
{
$x_pos = ($width - $height);
$y_pos = 0;
}
$new_width = $height;
$new_height = $height;
}
else if($height > $width) // Vertical Rectangle?
{
if($location == 'center')
{
$x_pos = 0;
$y_pos = ($height - $width) / 2;
$y_pos = ceil($y_pos);
}
else if($location == 'left')
{
$x_pos = 0;
$y_pos = 0;
}
else if($location == 'right')
{
$x_pos = 0;
$y_pos = ($height - $width);
}
$new_width = $width;
$new_height = $width;
}
$image = $image_create_func($this->source_image);
$new_image = ImageCreateTrueColor($new_width, $new_height);
// Crop to Square using the given dimensions
ImageCopy($new_image, $image, 0, 0, $x_pos, $y_pos, $width, $height);
if($this->save_to_folder)
{
if($this->new_image_name)
{
$new_name = $this->new_image_name.'.'.$new_image_ext;
}
else
{
$new_name = $this->new_image_name( basename($this->source_image) ).'_square_'.$location.'.'.$new_image_ext;
}
$save_path = $this->save_to_folder.$new_name;
}
else
{
/* Show the image (on the fly) without saving it to a folder */
header("Content-Type: ".$mime);
$image_save_func($new_image);
$save_path = '';
}
// Save image
$process = $image_save_func($new_image, $save_path) or die("There was a problem in saving the new file.");
return array('result' => $process, 'new_file_path' => $save_path);
}
}
function new_image_name($filename)
{
$string = trim($filename);
$string = strtolower($string);
$string = trim(ereg_replace("[^ A-Za-z0-9_]", " ", $string));
$string = ereg_replace("[ \t\n\r]+", "_", $string);
$string = str_replace(" ", '_', $string);
$string = ereg_replace("[ _]+", "_", $string);
return $string;
}
}
?>
This is an usage example of this class:
example.php
<?php
include 'crop.image.to.square.class.php';
$crop = new Crop_Image_To_Square;
$crop->source_image = 'my_rectangle_image.jpg';
$crop->save_to_folder = 'square_images/';
/* left, center or right; If none is set, center will be used as default */
$process = $crop->crop('right');
if($process['result'])
{
echo 'The rectangle image ('.$process['new_file_path'].') was cropped.';
}
?>
If you’re interested in resizing an image (i.e. to square) consider checking our post regarding images resizing.
Do you wish to receive the latest updates as soon as they are posted? Get our RSS Feed or Subscribe to the Newsletter!
- October 1, 2008
- article by Gabriel C.
- 4 comments
Sponsors
Related Posts
-
PHP: How to Add Transparency to an Image using GDat October 13, 2008 with 5 comments
-
PHP: How to Create Mirror Images using GDat January 19, 2009
-
Resize an Image (on the fly) & Keep its Aspect Ratio using PHP and GDat September 28, 2008 with 26 comments
-
PHP: How to Download a Remote Image using GD or cURLat January 5, 2009 with 16 comments
-
Image Cropping with jQuery, MooTools, Prototype & script.aculo.usat December 22, 2008

4 Replies to "PHP: Cropping a Rectangle Image to Square using GD"
October 30, 2008 at 2:38 PM
possible to set cropsize and size of image for thumbnail?
October 30, 2008 at 2:55 PM
This class just crops the image (as it is) to a square (in the left, center or right side). To resize an image please consider checking the Image Resize Class: http://www.bitrepository.com/web-programming/php/resizing-an-image.html.
January 26, 2009 at 8:50 AM
might want to consider using
imagecopyresampled
instead of just imagecopy
gives better quality
December 3, 2009 at 3:04 PM
demo pls, make a clearly