>打开原始图像
>创建一个新的空白图像.
>用您想要的背景颜色填充新图像
>使用ImageCopyResampled调整大小并复制以新图像为中心的原始图像
>保存新图像
您也可以使用switch语句
$img = imagecreatefromstring( file_get_contents ("path/to/image") );
这将自动检测图像类型(如果您的安装支持imagetype)
更新了代码示例
$orig_filename = 'c:\temp\380x253.jpg';
$new_filename = 'c:\temp\test.jpg';
list($orig_w, $orig_h) = getimagesize($orig_filename);
$orig_img = imagecreatefromstring(file_get_contents($orig_filename));
$output_w = 200;
$output_h = 200;
// determine scale based on the longest edge
if ($orig_h > $orig_w) {
$scale = $output_h/$orig_h;
} else {
$scale = $output_w/$orig_w;
}
// calc new image dimensions
$new_w = $orig_w * $scale;
$new_h = $orig_h * $scale;
echo "Scale: $scale
";
echo "New W: $new_w
";
echo "New H: $new_h
";
// determine offset coords so that new image is centered
$offest_x = ($output_w - $new_w) / 2;
$offest_y = ($output_h - $new_h) / 2;
// create new image and fill with background colour
$new_img = imagecreatetruecolor($output_w, $output_h);
$bgcolor = imagecolorallocate($new_img, 255, 0, 0); // red
imagefill($new_img, 0, 0, $bgcolor); // fill background colour
// copy and resize original image into center of new image
imagecopyresampled($new_img, $orig_img, $offest_x, $offest_y, 0, 0, $new_w, $new_h, $orig_w, $orig_h);
//save it
imagejpeg($new_img, $new_filename, 80);