php 生成缩略图
时间: 2023-08-18 14:09:59 浏览: 110
要在 PHP 中生成缩略图,可以使用 GD 库。以下是一个简单的示例代码:
```php
// 原始图片路径
$source_image = "path/to/image.jpg";
// 缩略图保存路径
$thumb_image = "path/to/thumb_image.jpg";
// 缩略图宽度
$thumb_width = 200;
// 缩略图高度
$thumb_height = 200;
// 获取原始图片信息
list($width, $height, $type) = getimagesize($source_image);
// 根据图片类型创建一个新的图片
switch ($type) {
case IMAGETYPE_JPEG:
$source = imagecreatefromjpeg($source_image);
break;
case IMAGETYPE_PNG:
$source = imagecreatefrompng($source_image);
break;
case IMAGETYPE_GIF:
$source = imagecreatefromgif($source_image);
break;
}
// 创建一个新的缩略图
$thumb = imagecreatetruecolor($thumb_width, $thumb_height);
// 将原始图片缩放到缩略图的大小
imagecopyresampled($thumb, $source, 0, 0, 0, 0, $thumb_width, $thumb_height, $width, $height);
// 保存缩略图
imagejpeg($thumb, $thumb_image, 80);
// 释放内存
imagedestroy($source);
imagedestroy($thumb);
```
以上代码中,我们使用 `getimagesize()` 函数获取原始图片的信息,然后根据图片类型使用相应的函数创建一个新的图片。`imagecreatetruecolor()` 函数创建一个指定大小的新图片,`imagecopyresampled()` 函数将原始图片缩放到缩略图的大小,最后使用 `imagejpeg()` 函数保存缩略图。记得在最后释放内存。
阅读全文