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;
	}
}
?>
Variables Info

$source – Here we set the full path (i.e. /home/www.mysite.com/public_html/images/myrectangle.jpg) to the rectangle image we wish to crop. If the image is in the same folder with the class, then you can just set the filename as the path (i.e. myrectangle.jpg).

$new_image_name – It’s used to set a name for the new cropped image. If it’s not set a name will be assigned automatically.

$save_to_folder – The path to the folder where the square image will be saved. Make sure it’s writable (0777). It no folder is set the new square image will show in the browser (on the fly) without being saved.

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!

Get our RSS Feed!

Sponsors

4 Replies to "PHP: Cropping a Rectangle Image to Square using GD"

  1. possible to set cropsize and size of image for thumbnail?

  2. 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.

  3. might want to consider using

    imagecopyresampled

    instead of just imagecopy

    gives better quality

Leave a Reply


* = required fields

(will not be published)


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


  

CommentLuv Enabled