SoFunction
Updated on 2025-04-07

PHP generates thumbnails to fill white edges (equal thumbnail scheme)


//The path to the source image can be a local file or a remote image
$src_path = '';
//The width of the final image is saved
$width = 160;
//The image is saved in the end
$height = 120;

// Source image object
$src_image = imagecreatefromstring(file_get_contents($src_path));
$src_width = imagesx($src_image);
$src_height = imagesy($src_image);

//Generate equal-scale thumbnails
$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 edge
$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 picture
header('Content-Type: image/jpeg');
imagejpeg($final_image);