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

2017-09-07 02:20:20 +08:00
 a523860
对大神来说应该很简单,可是对我小白捉磨了几天也不成功


搜索出来的,都只介绍了上传图片,加水印,保存图片的方法

于是把几篇文章的代码综合起来,还是不成功
1964 次点击
所在节点    PHP
3 条回复
815lbh
2017-09-07 09:20:51 +08:00
刚刚好有个 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;
}
}
linxl
2017-09-07 09:21:35 +08:00
Alex6
2017-09-07 15:43:33 +08:00
这种东西,github 搜索 php thumb。很多。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/388795

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX