Resize JPEG images using PHP

This is something I have had to do on numerous occasions, and each time I have to look up GD library functions and mess around with several attempts before I get it right, so I figured it was time I wrote a couple of simple PHP functions to handle this. Hopefully you can use them too…

Resize a JPEG to a maximum width and height whilst maintaining the aspect ratio (proportions).

Resize a JPEG whilst maintaining aspect ratio (proportions)

 $height) {

		// LANDSCAPE
		$new_width = $w;
		$new_height = round($height * ($w / $width));
		if ($new_height > $h) {
			$new_height = $h;
			$new_width = round($width * ($h / $height));
		}

	} else {

		// PORTRAIT
		$new_height = $h;
		$new_width = round($width * ($h / $height));
		if ($new_width > $w) {
			$new_width = $w;
			$new_height = round($height * ($w / $width));
		}
	}

	// OPEN IMAGES IN MEMORY
	$source = imagecreatefromjpeg($orig);
	$thumb = imagecreatetruecolor($new_width,$new_height);

	// RESIZE
	imagecopyresized($thumb, $source, 0, 0, 0, 0,
		$new_width, $new_height, $width, $height);

	// SAVE RESIZED
	imagejpeg($thumb, $dest, 90);

	// DESTROY IMAGES IN MEMORY
	imagedestroy($source);
	imagedestroy($thumb);
}
?>

Sometimes you don’t want to maintain your image’s aspect ratio, you want to resize and crop all images to the same height and width, and for that I created a second function:

Resize and crop a JPEG to a specific width and height

Resize and crop a JPEG to a specific size

 $height) {

		// LANDSCAPE
		$new_height = $h;
		$new_width = round($width * ($h / $height));
		$y_offset = 0;
		// POSITION IN THE CENTER FOR LANDSCAPE
		$x_offset = ($new_width - $w) / 2);
		if ($x_offset < 0) {
			$new_width = $w;
			$new_height = round($height * ($w / $width));
			$x_offset = 0;
			// WE ERR MORE TO THE TOP ON PORTRAIT
			$y_offset = ($new_height - $h) / 4);
		}

	} else {

		// PORTRAIT
		$new_width = $w;
		$new_height = round($height * ($w / $width));
		$x_offset = 0;
		// WE ERR MORE TO THE TOP ON PORTRAIT
		$y_offset = ($new_height - $h) / 4);
		if ($y_offset < 0) {
			$new_height = $h;
			$new_width = round($width * ($h / $height));
			$y_offset = 0;
			// POSITION IN THE CENTER FOR LANDSCAPE
			$x_offset = ($new_width - $w) / 2); 		}
	}

	// OPEN IMAGES IN MEMORY
	$source = imagecreatefromjpeg($orig);
	$thumb = imagecreatetruecolor($h,$w);

	// RESIZE AND CROP
	imagecopyresized($thumb, $source, $x_offset, $y_offset, 0, 0,
		$new_width, $new_height, $width, $height);

	// SAVE RESIZED
	imagejpeg($thumb, $dest, 90);

	// DESTROY IMAGES IN MEMORY
	imagedestroy($source);
	imagedestroy($thumb);
}
?>

One thought on “Resize JPEG images using PHP

  1. many thanks for this code, this was what ı am looking for…
    I will try soonest. Thanks again and again, I will follow your blog and share.

Leave a Reply

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