刚刚好有个 util
<?php
class FileUtil
{
/**
* 生成图片的缩略图。
* 缩略图生成后存放在原图同一目录下;
* 缩略图名称为:thumbnail_(原图名称).jpg
*
* @
param String $pathImage 原图的相对路径
* @
param float $sizeRatio 宽高压缩率:1~0.1
* @
return String $thumbnailPath 返回缩略图的相对路径
*/
public function generateImageThumbnail($pathImage, $sizeRatio = 0.5)
{
$publicPathImage = public_path($pathImage);
// 检查文件存在
if (!is_file($publicPathImage)) {
return $pathImage;
}
// 获取原图尺寸和根据路径生成原图 response 对象
list($width, $height, $imgType, $src_image) = $this->extractImageSizeAndResponse($publicPathImage);
if (!in_array($imgType, array(1, 2, 3))) {
return $pathImage;
}
// 缩放后尺寸
$newWidth = $width * $sizeRatio;
$newHeight = $height * $sizeRatio;
// 生成指定宽高的空白缓冲区
$dst_image = imagecreatetruecolor($newWidth, $newHeight);
$whiteColor = imagecolorAllocate($dst_image, 255, 255, 255);
imagefill($dst_image, 0, 0, $whiteColor);
// 将原图文件内容复制到空白缓冲区
imagecopyresampled($dst_image, $src_image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
// 获得缩略图存放位置
$thumbnailPath = $this->extractThumbnailDir($pathImage);
// 把缩略图放进指定位置
switch ($imgType) {
case 1: // IMAGETYPE_GIF
imagegif($dst_image, public_path($thumbnailPath));
break;
case 2: // IMAGETYPE_JPEG
imagejpeg($dst_image, public_path($thumbnailPath));
break;
case 3: // IMAGETYPE_PNG
imagepng($dst_image, public_path($thumbnailPath));
break;
default:
return $pathImage;
}
imagedestroy($dst_image);
return $thumbnailPath;
}
private function extractThumbnailDir($filePath)
{
$index = strrpos($filePath, '/');
$dir = substr($filePath, 0, $index);
$fileName = substr($filePath, $index + 1);
return $dir . '/thumbnail_' . $fileName;
}
private function extractImageSizeAndResponse($publicPathImage)
{
// getimagesize() 如果不存在或非图片文件会返回 false 并产生 E_WARNING 级错误
$imageSize = getimagesize($publicPathImage);
if ($imageSize == false) {
return array();
}
switch ($imageSize[2]) {
case 1: // IMAGETYPE_GIF
$imageSize[3] = imagecreatefromgif($publicPathImage);
break;
case 2: // IMAGETYPE_JPEG
$imageSize[3] = imagecreatefromjpeg($publicPathImage);
break;
case 3: // IMAGETYPE_PNG
$imageSize[3] = imagecreatefrompng($publicPathImage);
break;
default:
return array();
}
return $imageSize;
}
}