本文目录导读:

我来详细介绍PHP生成图片缩略图的几种常用方法:
使用GD库(最常用)
基本缩略图生成函数
<?php
/**
* 生成缩略图
* @param string $source 原图路径
* @param string $target 缩略图保存路径
* @param int $width 缩略图宽度
* @param int $height 缩略图高度
* @param bool $crop 是否裁剪
* @return bool
*/
function createThumbnail($source, $target, $width, $height, $crop = false) {
// 检查原图是否存在
if (!file_exists($source)) {
return false;
}
// 获取原图信息
list($srcWidth, $srcHeight, $type) = getimagesize($source);
// 根据图片类型创建画布
switch ($type) {
case IMAGETYPE_JPEG:
$srcImage = imagecreatefromjpeg($source);
break;
case IMAGETYPE_PNG:
$srcImage = imagecreatefrompng($source);
break;
case IMAGETYPE_GIF:
$srcImage = imagecreatefromgif($source);
break;
default:
return false;
}
// 计算缩放比例
if ($crop) {
// 裁剪模式:先缩放后裁剪
$ratio = max($width/$srcWidth, $height/$srcHeight);
$newWidth = $srcWidth * $ratio;
$newHeight = $srcHeight * $ratio;
// 创建临时画布
$tempImage = imagecreatetruecolor($newWidth, $newHeight);
// 保持PNG透明度
if ($type == IMAGETYPE_PNG) {
imagealphablending($tempImage, false);
imagesavealpha($tempImage, true);
}
imagecopyresampled($tempImage, $srcImage, 0, 0, 0, 0,
$newWidth, $newHeight, $srcWidth, $srcHeight);
// 裁剪到目标尺寸
$thumbImage = imagecreatetruecolor($width, $height);
if ($type == IMAGETYPE_PNG) {
imagealphablending($thumbImage, false);
imagesavealpha($thumbImage, true);
}
$cropX = ($newWidth - $width) / 2;
$cropY = ($newHeight - $height) / 2;
imagecopy($thumbImage, $tempImage, 0, 0, $cropX, $cropY,
$width, $height);
imagedestroy($tempImage);
} else {
// 等比例缩放模式
$ratio = min($width/$srcWidth, $height/$srcHeight);
$newWidth = $srcWidth * $ratio;
$newHeight = $srcHeight * $ratio;
$thumbImage = imagecreatetruecolor($newWidth, $newHeight);
if ($type == IMAGETYPE_PNG) {
imagealphablending($thumbImage, false);
imagesavealpha($thumbImage, true);
}
imagecopyresampled($thumbImage, $srcImage, 0, 0, 0, 0,
$newWidth, $newHeight, $srcWidth, $srcHeight);
}
// 保存缩略图
$result = false;
switch ($type) {
case IMAGETYPE_JPEG:
$result = imagejpeg($thumbImage, $target, 80);
break;
case IMAGETYPE_PNG:
$result = imagepng($thumbImage, $target, 8);
break;
case IMAGETYPE_GIF:
$result = imagegif($thumbImage, $target);
break;
}
// 释放内存
imagedestroy($thumbImage);
imagedestroy($srcImage);
return $result;
}
// 使用示例
$source = 'uploads/image.jpg';
$target = 'uploads/thumb_image.jpg';
createThumbnail($source, $target, 200, 150, true);
?>
等比例缩放(保持宽高比)
<?php
function createThumbnailFixed($source, $target, $maxWidth, $maxHeight) {
list($origWidth, $origHeight) = getimagesize($source);
// 计算缩放比例
$widthRatio = $maxWidth / $origWidth;
$heightRatio = $maxHeight / $origHeight;
$ratio = min($widthRatio, $heightRatio);
$newWidth = (int)$origWidth * $ratio;
$newHeight = (int)$origHeight * $ratio;
$image_p = imagecreatetruecolor($newWidth, $newHeight);
$image = imagecreatefromjpeg($source);
imagecopyresampled($image_p, $image, 0, 0, 0, 0,
$newWidth, $newHeight, $origWidth, $origHeight);
imagejpeg($image_p, $target, 80);
imagedestroy($image_p);
imagedestroy($image);
}
?>
使用Imagick库(功能更强大)
<?php
/**
* 使用Imagick生成缩略图
* @param string $source 原图路径
* @param string $target 目标路径
* @param int $width 宽度
* @param int $height 高度
*/
function createThumbnailImagick($source, $target, $width, $height) {
try {
$imagick = new \Imagick($source);
// 等比例缩放
$imagick->thumbnailImage($width, $height, true);
// 或者裁剪到固定尺寸
// $imagick->cropThumbnailImage($width, $height);
// 设置图片质量
$imagick->setImageCompressionQuality(80);
// 保存
$imagick->writeImage($target);
$imagick->clear();
return true;
} catch (Exception $e) {
return false;
}
}
// 使用示例
createThumbnailImagick('image.jpg', 'thumb.jpg', 200, 150);
?>
批量生成缩略图
<?php
/**
* 批量生成缩略图
* @param string $sourceDir 源图片目录
* @param string $targetDir 缩略图目录
* @param int $width 宽度
* @param int $height 高度
*/
function batchCreateThumbnails($sourceDir, $targetDir, $width, $height) {
// 创建目标目录
if (!file_exists($targetDir)) {
mkdir($targetDir, 0755, true);
}
// 获取所有图片文件
$files = glob($sourceDir . '/*.{jpg,jpeg,png,gif}', GLOB_BRACE);
foreach ($files as $file) {
$filename = basename($file);
$target = $targetDir . '/' . $filename;
// 生成缩略图
if (!file_exists($target)) {
createThumbnail($file, $target, $width, $height);
}
}
}
// 使用示例
batchCreateThumbnails('uploads/original', 'uploads/thumbnails', 200, 150);
?>
注意事项
1 检查GD库是否安装
<?php
// 检查GD库是否可用
if (extension_loaded('gd') && function_exists('gd_info')) {
echo "GD库已安装";
} else {
echo "需要安装GD库";
}
?>
2 内存优化
<?php
// 处理大图片时增加内存限制
ini_set('memory_limit', '256M');
set_time_limit(300); // 5分钟超时
?>
完整示例类
<?php
class ImageThumbnail {
private $source;
private $target;
private $width;
private $height;
private $quality;
public function __construct($source, $target, $width, $height, $quality = 80) {
$this->source = $source;
$this->target = $target;
$this->width = $width;
$this->height = $height;
$this->quality = $quality;
}
public function generate() {
if (!file_exists($this->source)) {
throw new Exception("源文件不存在");
}
// 确保目录存在
$dir = dirname($this->target);
if (!is_dir($dir)) {
mkdir($dir, 0755, true);
}
return $this->process();
}
private function process() {
list($srcWidth, $srcHeight, $type) = getimagesize($this->source);
// 计算等比例缩放尺寸
$ratio = min($this->width/$srcWidth, $this->height/$srcHeight);
$newWidth = $srcWidth * $ratio;
$newHeight = $srcHeight * $ratio;
$thumbImage = imagecreatetruecolor($newWidth, $newHeight);
$srcImage = $this->createSourceImage($type);
if ($type == IMAGETYPE_PNG) {
imagealphablending($thumbImage, false);
imagesavealpha($thumbImage, true);
}
imagecopyresampled($thumbImage, $srcImage, 0, 0, 0, 0,
$newWidth, $newHeight, $srcWidth, $srcHeight);
$result = $this->saveImage($type, $thumbImage);
imagedestroy($thumbImage);
imagedestroy($srcImage);
return $result;
}
private function createSourceImage($type) {
switch ($type) {
case IMAGETYPE_JPEG:
return imagecreatefromjpeg($this->source);
case IMAGETYPE_PNG:
return imagecreatefrompng($this->source);
case IMAGETYPE_GIF:
return imagecreatefromgif($this->source);
default:
throw new Exception("不支持的图片格式");
}
}
private function saveImage($type, $image) {
switch ($type) {
case IMAGETYPE_JPEG:
return imagejpeg($image, $this->target, $this->quality);
case IMAGETYPE_PNG:
return imagepng($image, $this->target, 9);
case IMAGETYPE_GIF:
return imagegif($image, $this->target);
default:
return false;
}
}
}
// 使用示例
try {
$thumb = new ImageThumbnail('image.jpg', 'thumb.jpg', 200, 150);
$thumb->generate();
echo "缩略图生成成功";
} catch (Exception $e) {
echo "错误: " . $e->getMessage();
}
?>
- GD库:最常用,支持JPG/PNG/GIF,功能基本满足需求
- Imagick:功能更强大,处理大图片效果更好
- 等比例缩放:保持图片原始宽高比
- 裁剪模式:生成固定尺寸,可能裁剪部分内容
- 注意内存:大图片处理可能需要调整PHP配置
选择哪种方式取决于你的具体需求和服务器环境配置。