I wrote this function long time ago and I have used it so many since then. I decided to publish it.
You can find plenty of similar functions but this one is a little bit different. As a parameter you specify new MAX dimensions so image will be scaled based on its height or width. I believe I have enough comments in the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | public function resize($source_image, $target_image, $new_width, $new_height) { // get current size list($width, $height) = @getimagesize($source_image); if ($width > $new_width || $height > $new_height) { $scale1 = $width / $new_width; $scale2 = $height / $new_height; // check if we should scale using width or height $scale = $scale1 > $scale2 ? $scale1 : $scale2; // make sure we scale correctly $new_height = floor($height / $scale); $new_width = floor($width / $scale); // Load $thumb = imagecreatetruecolor($new_width, $new_height); $source = imagecreatefromjpeg($source_image); // Resize imagecopyresampled($thumb, $source, 0, 0, 0, 0, $new_width, $new_height, $width, $height); // Save the file at 95% quality imagejpeg($thumb, $target_image, 95); } else { // image small already - don't resize copy($source_image, $target_image); } } |