Here is a PHP function that resizes an image to fit within a specified maximum width and height, preserving its aspect ratio. This can be useful if you’re working with WordPress or a similar PHP-based platform:
function resize_image($source_path, $destination_path, $max_width, $max_height) {
// Get original image dimensions and type
list($orig_width, $orig_height, $image_type) = getimagesize($source_path);
// Calculate the aspect ratio
$aspect_ratio = $orig_width / $orig_height;
// Determine new dimensions based on max width and height while preserving aspect ratio
if ($max_width / $max_height > $aspect_ratio) {
$new_width = (int)($max_height * $aspect_ratio);
$new_height = $max_height;
} else {
$new_width = $max_width;
$new_height = (int)($max_width / $aspect_ratio);
}
// Create a new empty image with the calculated dimensions
$new_image = imagecreatetruecolor($new_width, $new_height);
// Load the source image based on its type
switch ($image_type) {
case IMAGETYPE_JPEG:
$source_image = imagecreatefromjpeg($source_path);
break;
case IMAGETYPE_PNG:
$source_image = imagecreatefrompng($source_path);
// Preserve transparency for PNG images
imagealphablending($new_image, false);
imagesavealpha($new_image, true);
break;
case IMAGETYPE_GIF:
$source_image = imagecreatefromgif($source_path);
break;
default:
return false; // Unsupported image type
}
// Resize the original image into the new image
imagecopyresampled($new_image, $source_image, 0, 0, 0, 0, $new_width, $new_height, $orig_width, $orig_height);
// Save the new image based on its type
switch ($image_type) {
case IMAGETYPE_JPEG:
imagejpeg($new_image, $destination_path);
break;
case IMAGETYPE_PNG:
imagepng($new_image, $destination_path);
break;
case IMAGETYPE_GIF:
imagegif($new_image, $destination_path);
break;
}
// Free up memory
imagedestroy($source_image);
imagedestroy($new_image);
return true;
}
Usage
$source_path = 'path/to/original/image.jpg';
$destination_path = 'path/to/resized/image.jpg';
$max_width = 800; // Max width in pixels
$max_height = 600; // Max height in pixels
resize_image($source_path, $destination_path, $max_width, $max_height);
Explanation
- Aspect Ratio: The function maintains the aspect ratio by checking whether width or height is the limiting factor based on the provided maximum dimensions.
- Transparency: Special handling is added for PNG images to preserve transparency.
- Supported Formats: This function supports JPEG, PNG, and GIF formats.