一、选择合适的图片处理库

二、准备图片资源

$imagePath = 'path/to/your/image.jpg';

三、检查图片是否存在

if (!file_exists($imagePath)) {
    die('图片不存在');
}

四、获取图片信息

list($width, $height) = getimagesize($imagePath);

五、计算缩略图尺寸

$thumbnailWidth = 100;
$ratio = $thumbnailWidth / $width;
$thumbnailHeight = $height * $ratio;

六、创建缩略图图像

使用GD库创建一个新的图像资源。

$thumbnailImage = imagecreatetruecolor($thumbnailWidth, $thumbnailHeight);

七、复制图片内容到缩略图

$imageType = mime_content_type($imagePath);
switch ($imageType) {
    case 'image/jpeg':
        $sourceImage = imagecreatefromjpeg($imagePath);
        break;
    case 'image/png':
        $sourceImage = imagecreatefrompng($imagePath);
        break;
    case 'image/gif':
        $sourceImage = imagecreatefromgif($imagePath);
        break;
    default:
        die('不支持的图片格式');
}

imagecopyresampled($thumbnailImage, $sourceImage, 0, 0, 0, 0, $thumbnailWidth, $thumbnailHeight, $width, $height);

八、输出缩略图

将生成的缩略图输出到浏览器或保存到服务器。

imagejpeg($thumbnailImage, 'path/to/save/thumbnail.jpg');

或者,直接输出到浏览器:

header('Content-Type: image/jpeg');
imagejpeg($thumbnailImage);

九、清理资源

在完成缩略图的生成后,释放图像资源。

imagedestroy($thumbnailImage);
imagedestroy($sourceImage);

总结