PHP实现图片等比缩放示例代码
function resize_image_with_alpha($source, $max_width, $max_height) {
// 检查源文件是否存在
if (!file_exists($source)) {
return false;
}
// 获取原始图片尺寸和类型
$size = getimagesize($source);
if ($size === false) {
return false;
}
list($width, $height, $type) = $size;
// 计算缩放比例因子,保持长宽比并确保不超过最大尺寸
$scale = min($max_width / $width, $max_height / $height);
$new_width = (int)$width * $scale;
$new_height = (int)$height * $scale;
// 如果不需要缩放,直接返回原文件路径
if ($scale == 1.0) {
return $source;
}
// 创建原始图片资源和新的图像画布
switch ($type) {
case IMAGETYPE_JPEG:
$src_img = imagecreatefromjpeg($source);
break;
case IMAGETYPE_PNG:
$src_img = imagecreatefrompng($source);
break;
case IMAGETYPE_GIF:
$src_img = imagecreatefromgif($source);
break;
default:
return false; // 不支持的图片类型
}
$dest_img = imagecreatetruecolor($new_width, $new_height);
if ($type == IMAGETYPE_PNG) {
// 处理透明背景
imagesavealpha($dest_img, true);
$transparent_color = imagecolorallocatealpha($dest_img, 0, 0, 0, 127); // 完全透明的颜色
imagefill($dest_img, 0, 0, $transparent_color);
}
// 复制图像数据到新画布
imagecopyresampled(
$dest_img,
$src_img,
0, 0,
0, 0,
$new_width,
$new_height,
$width,
$height
);
// 生成新的文件名
$directory = dirname($source);
$baseName = basename($source, '.' . image_type_to_extension($type)); // 去掉原来后缀
$extension = image_type_to_extension($type, false); // 不带点的扩展名
$destination = $directory . '/...