php生成缩略图示例代码分享(使用gd库实现)


当然,以下是一个使用PHP的GD库来生成缩略图的示例代码。这段代码会加载一个图片文件,然后根据指定的宽度和高度生成缩略图,并保持图片的宽高比不变。


<?php
function createThumbnail($sourceImagePath, $thumbnailPath, $thumbnailWidth, $thumbnailHeight) {
    // 检查GD库是否安装
    if (!extension_loaded('gd')) {
        die('GD库未安装,无法生成缩略图。');
    }

    // 获取原始图片信息
    list($sourceWidth, $sourceHeight, $sourceType) = getimagesize($sourceImagePath);

    // 根据原图尺寸和缩略图尺寸计算缩放比例
    $sourceAspectRatio = $sourceWidth / $sourceHeight;
    $thumbnailAspectRatio = $thumbnailWidth / $thumbnailHeight;

    if ($sourceAspectRatio > $thumbnailAspectRatio) {
        // 源图更宽,按高度缩放
        $thumbnailWidth = (int) ($thumbnailHeight * $sourceAspectRatio);
    } else {
        // 源图更高,或宽高比相同,按宽度缩放
        $thumbnailHeight = (int) ($thumbnailWidth / $sourceAspectRatio);
    }

    // 根据图片类型创建图片资源
    switch ($sourceType) {
        case IMAGETYPE_GIF:
            $sourceGdImage = imagecreatefromgif($sourceImagePath);
            break;
        case IMAGETYPE_JPEG:
            $sourceGdImage = imagecreatefromjpeg($sourceImagePath);
            break;
        case IMAGETYPE_PNG:
            $sourceGdImage = imagecreatefrompng($sourceImagePath);
            break;
        default:
            die('不支持的图片格式。');
    }

    // 创建一个新图片资源
    $thumbnailGdImage = imagecreatetruecolor($thumbnailWidth, $thumbnailHeight);

    // 复制并调整大小
    imagecopyresampled($thumbnailGdImage, $sourceGdImage, 0, 0, 0, 0, $thumbnailWidth, $thumbnailHeight, $sourceWidth, $sourceHeight);

    // 根据图片类型保存缩略图
    switch ($sourceType) {
        case IMAGETYPE_GIF:
            imagegif($thumbnailGdImage, $thumbnailPath);
            break;
        case IMAGETYPE_JPEG:
            imagejpeg($thumbnailGdImage, $thumbnailPath, 90); // 90% 压缩质量
            break;
        case IMAGETYPE_PNG:
            imagepng($thumbnailGdImage, $thumbnailPath, 9); // 0 (非压缩) 到 9 (无损失)
            break;
    }

    // 释放内存
    imagedestroy($sourceGdImage);
    imagedestroy($thumbnailGdImage);

    echo "缩略图已生成在: " . $thumbnailPath;
}

// 使用示例
$sourceImagePath = 'path/to/your/image.jpg';
$thumbnailPath = 'path/to/your/thumbnail.jpg';
$thumbnailWidth = 100;
$thumbnailHeight = 100;

createThumbnail($sourceImagePath, $thumbnailPath, $thumbnailWidth, $thumbnailHeight);
?>

请确保将`$sourceImagePath`和`$thumbnailPath`变量替换为您的图片源路径和目标缩略图路径。这段代码会生成一个保持宽高比、最大宽度和高度分别为指定值的缩略图。