Looking to resize images to set dimensions of (1080x1350) without cropping, just fill the dead space with black boarders/buffers.
As we can’t control what size and aspect ratios users uploads images. Im looking to create a php function that creates a ‘canvas’ that has set dimensions of 1080x1350.
I then place the users image in the middle this ‘canvas’ (without cropping) and fill any dead space with black boards.
You’re almost there with your approach! To create a black-bordered canvas for any image, you just need to make a couple of adjustments:
Changes to Make:
Create a Black Background: Instead of using a transparent background, allocate a solid black color to fill the canvas.
Image Filling Logic: Make sure you correctly center the image on the canvas.
Here’s an updated version of your code to achieve that:
php
Copy code
// original image size
$width = imagesx($image);
$height = imagesy($image);
// canvas size
$thumb_width = 1080;
$thumb_height = 1350;
$original_aspect = $width / $height;
$thumb_aspect = $thumb_width / $thumb_height;
if ($original_aspect >= $thumb_aspect) {
// Fit to height
$new_height = $thumb_height;
$new_width = $width / ($height / $thumb_height);
} else {
// Fit to width
$new_width = $thumb_width;
$new_height = $height / ($width / $thumb_width);
}
// Create canvas
$tmp = imagecreatetruecolor($thumb_width, $thumb_height);
// Fill with black background
$black = imagecolorallocate($tmp, 0, 0, 0);
imagefill($tmp, 0, 0, $black);
// Center the resized image
$x_offset = round(($thumb_width - $new_width) / 2);
$y_offset = round(($thumb_height - $new_height) / 2);
// Resize and place the image in the middle
imagecopyresampled($tmp, $image, $x_offset, $y_offset, 0, 0, round($new_width), round($new_height), round($width), round($height));
// Save or output the image
imagejpeg($tmp, 'output_image.jpg'); // Or any other preferred format
// Clean up
imagedestroy($tmp);
imagedestroy($image);
Key Adjustments:
Black background: $black = imagecolorallocate($tmp, 0, 0, 0); ensures the dead space is filled with black instead of transparent.
Centering the image: $x_offset and $y_offset are calculated to properly position the image in the middle of the canvas.
This should achieve the result you’re aiming for: an image placed in the middle of a black 1080x1350 canvas without cropping, with the extra space filled in with black borders.