php 图片缩放保存,救一段 PHP 上传图片并缩小尺寸保存的代码

1

2017-09-07 09:20:51 +08:00

刚刚好有个 util

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;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值