PHP 生成图片 图片按照比例压缩, 图片居中背景大小固定
PHP 7.0
需求:上传任意大小图片,按照宽高比例压缩,生成固定大小的图片,不足的地方用白边补齐
$height = $width = 400;
$file_info = @getimagesize($filename);
$orig_width = $file_info[0] ?? 0;
$orig_height = $file_info[1] ?? 0;
$file_type = $file_info['mime'] ?? '';
// 生成等比例缩放图
$tmp_image_width = 0;
$tmp_image_height = 0;
if ($orig_width / $orig_height >= $width / $height) {
$tmp_image_width = $width;
$tmp_image_height = round($tmp_image_width * $orig_height / $orig_width);
} else {
$tmp_image_height = $height;
$tmp_image_width = round($tmp_image_height * $orig_width / $orig_height);
}
$tmp_image = imagecreatetruecolor($tmp_image_width, $tmp_image_height);
$orgi_image = @imagecreatefromjpeg($filename);
imagecopyresampled($tmp_image, $orgi_image, 0, 0, 0, 0, $tmp_image_width, $tmp_image_height, $orig_width, $orig_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, $tmp_image, $x, $y, 0, 0, $tmp_image_width, $tmp_image_height);
// 输出
$preview_img_name = 'square_img.jpg';
imagejpeg($final_image, $preview_img_name, 100);
imagedestroy($orgi_image);
imagedestroy($tmp_image);
imagedestroy($final_image);
还没有评论,来说两句吧...