Resize and crop image from center with PHP

Sometimes I need to not only resize the image, but also to change its size by removing unnecessary edges for new size. This function changes image size and if the height or width is too large after resizing then the edges are cut off from the center. Input image formats are jpeg, gif, png.

//resize and crop image by center
function resize_crop_image($max_width, $max_height, $source_file, $dst_dir, $quality = 80){
	$imgsize = getimagesize($source_file);
	$width = $imgsize[0];
	$height = $imgsize[1];
	$mime = $imgsize['mime'];

		case 'image/gif':
			$image_create = "imagecreatefromgif";
			$image = "imagegif";

		case 'image/png':
			$image_create = "imagecreatefrompng";
			$image = "imagepng";
			$quality = 7;

		case 'image/jpeg':
			$image_create = "imagecreatefromjpeg";
			$image = "imagejpeg";
			$quality = 80;

			return false;
	$dst_img = imagecreatetruecolor($max_width, $max_height);
	$src_img = $image_create($source_file);
	$width_new = $height * $max_width / $max_height;
	$height_new = $width * $max_height / $max_width;
	//if the new width is greater than the actual width of the image, then the height is too large and the rest cut off, or vice versa
	if($width_new > $width){
		//cut point by height
		$h_point = (($height - $height_new) / 2);
		//copy image
		imagecopyresampled($dst_img, $src_img, 0, 0, 0, $h_point, $max_width, $max_height, $width, $height_new);
		//cut point by width
		$w_point = (($width - $width_new) / 2);
		imagecopyresampled($dst_img, $src_img, 0, 0, $w_point, 0, $max_width, $max_height, $width_new, $height);
	$image($dst_img, $dst_dir, $quality);

//usage example
resize_crop_image(100, 100, "test.jpg", "test.jpg");
This entry was posted in Programming and tagged , , , . Bookmark the permalink.

8 Responses to Resize and crop image from center with PHP

  1. Carlos

    It's just what I was looking for!! Thank you very much!!

    • You are welcome! I just found there is not set quality for jpeg, so I added $quality = 80; in line 23, else imagejpeg function will use default value 75.

  2. hungdungktv


  3. Thanks a lot !
    Works great from scratch. Adjusted it for my project with success. :)

  4. berhane

    Thanx buddy for this! haven't implemented it yet, but seems as others have had great success with it.

    Thanks for sharing - highly appreciated!

  5. Van

    Good JOB

  6. Dino

    Just perfect!

  7. Works perfect, thank you

Leave a Reply

Your email address will not be published. Required fields are marked *

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