PHP实现等比缩略图并填充白边方案
在网站开发中,上传图像后自动生成缩略图是一项高频需求。为了保持界面视觉统一,通常要求所有缩略图拥有相同的固定尺寸,例如近期项目中要求的160×120像素规格。然而,若源图比例与目标尺寸不符,强行拉伸或压缩会造成图像失真,严重影响用户体验。为此,采用“等比缩放+添加白边”的策略成为一种有效的解决方案。
原始输入图片尺寸为600×366像素:

经过处理后生成的最终效果图如下:

实现该功能的代码篇幅稍长,以下简要梳理核心逻辑思路:
首先,依据源图比例计算出缩略图的尺寸,确保其宽度不超过160像素且高度不超过120像素。以示例图片为例,计算出的中间缩略图尺寸为160×98像素。接着,创建一个160×120像素的白色背景画布,将上述缩略图居中绘制在该画布上即可达成效果。具体实现代码如下:
复制代码 代码如下: //源图的路径,可以是本地文件,也可以是远程图片 $src_path = '1.jpg'; //最终保存图片的宽 $width = 160; //最终保存图片的高 $height = 120;
//源图对象 $src_image = imagecreatefromstring(file_get_contents($src_path)); $src_width = imagesx($src_image); $src_height = imagesy($src_image);
//生成等比例的缩略图 $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);
//添加白边 $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);
//输出图片 header('Content-Type: image/jpeg'); imagejpeg($final_image);