It should be a very common function for a website to generate thumbnails after uploading images. Generally speaking, in order for the website to display beautifully, the thumbnails will be the same size. For example, for a website I recently built, the thumbnail specifications are all 160×120. . However, if the proportion of the uploaded image is inconsistent with the thumbnail, direct scaling will cause the image to be deformed, and the experience will definitely be bad. So the author thought of a compromise, which is to add white edges after reducing the size.
Source image, size is 600×366:
The final rendering:
The code is relatively long, let’s briefly talk about the idea:
First generate a thumbnail in proportion to the source image, and the width should not be larger than 160 and the height should not be larger than 120. For example, the above image will first generate a 160×98 thumbnail.
Create a new 160×120 white background image, center the thumbnail generated in the previous step on this image and it’s OK.
The final code is as follows:
//Source image object
$src_image = imagecreatefromstring(file_get_contents($src_path));
$src_width = imagesx($src_image);
$src_height = imagesy($src_image);
//Generate thumbnails of equal proportions
$tmp_image_width = 0;
$tmp_image_height = 0;
if ($src_width / $src_height >= $width / $height) {
$tmp_image_width = $width;
$tmp_image_height = round($tmp_image_width * $src_height / $src_width);
} else {
$tmp_image_height = $height;
$tmp_image_width = round($tmp_image_height * $src_width / $src_height);
}
$tmpImage = imagecreatetruecolor($tmp_image_width, $tmp_image_height);
imagecopyresampled($tmpImage, $src_image, 0, 0, 0, 0, $tmp_image_width, $tmp_image_height, $src_width, $src_height);
//Add white border
$final_image = imagecreatetruecolor($width, $height);
$color = imagecolorallocate($final_image, 255, 255, 255);
imagefill($final_image, 0 , 0, $color);
$x = round(($width - $tmp_image_width) / 2);
$y = round(($height - $tmp_image_height) / 2);
imagecopy($final_image, $tmpImage, $x, $y, 0, 0, $tmp_image_width, $tmp_image_height);
//Output image
header('Content-Type: image/jpeg');
imagejpeg($final_image);