Welcome

首页 / 网页编程 / PHP / PHP实现图片等比缩放示例代码

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 . '/' . $baseName . '_resized.' . $extension;

    // 保存新的图像文件
    switch ($type) {
        case IMAGETYPE_JPEG:
            imagejpeg($dest_img, $destination, 100);
            break;
        case IMAGETYPE_PNG:
            imagepng($dest_img, $destination, 9); // 使用最大压缩级别
            break;
        case IMAGETYPE_GIF:
            imagegif($dest_img, $destination);
            break;
    }

    // 释放内存
    imagedestroy($src_img);
    imagedestroy($dest_img);

    return $destination; // 返回新的文件路径
}

// 示例用法:
$source_path = 'input.png';
$max_width = 400;
$max_height = 300;

$result_path = resize_image_with_alpha($source_path, $max_width, $max_height);
if ($result_path) {
    echo "图片已成功缩放为:{$result_path}";
} else {
    echo "错误,请检查输入路径和类型。";
}