php 图像生成缩略图
参考自 https://blog.csdn.net/maoxinwen1/article/details/79202442
3D全景图过大(5M左右),导致一些不需要加载全景图的页面过慢,所以增加了和全景图一样名字的400X400的缩略图(20k左右),写个脚本初始化150个G的图片数据。
<?php
$dir= '/var/www/html/upload/siteimg3d';
/** * 生成缩略图并拷贝到指定位置 * * @param [type] $file 原图片路径 dir/1.jpg * @param [type] $newPath 移动到的位置 newDir * @param string $newName 生成的缩略图名称 new.jpg * @param integer $width 宽 400 * @param integer $height 高 400 * @param integer $per 缩放比例 为0不缩放,>0忽略参数2、3的宽高 * @return string || boolean newName || false */
function imageResize($file, $newPath, $newName = '', $width = 400, $height = 400, $per = 0)
{
if (!file_exists($file) || !$newPath) return false;
$imagedata = file_get_contents($file);
// 1 = GIF,2 = JPG,3 = PNG,4 = SWF,5 = PSD,6 = BMP,7 = TIFF(intel byte order),8 = TIFF(motorola byte order),
// 9 = JPC,10 = JP2,11 = JPX,12 = JB2,13 = SWC,14 = IFF,15 = WBMP,16 = XBM
list($bigWidth, $bigHight, $bigType) = getimagesizefromstring($imagedata); // 获取图像信息
if ($per > 0) { // 缩放比例
$width = $bigWidth * $per;
$height = $bigHight * $per;
}
$block = imagecreatetruecolor($width, $height); // 创建缩略图画板
imagealphablending($block, false); // 启用混色模式
imagesavealpha($block, true); // 保存PNG alpha通道信息
$bigImg = imagecreatefromstring($imagedata); // 创建原图画板
imagecopyresampled($block, $bigImg, 0, 0, 0, 0, $width, $height, $bigWidth, $bigHight); // 缩放
$tmpFilename = tempnam(sys_get_temp_dir(), 'image_'); // 生成临时文件名
$suffix = '';
switch ($bigType) { // 保存
case 1:
imagegif($block, $tmpFilename);
$suffix = '.gif';
break;
case 2:
imagejpeg($block, $tmpFilename);
$suffix = '.jpg';
break;
case 3:
imagepng($block, $tmpFilename);
$suffix = '.png';
break;
}
imagedestroy($block); // 销毁
if (!file_exists($newPath)) CreateDir($newPath);
if ($newName == '') {
$newName = time() . rand(100000, 999999) . $suffix;
}
copy($tmpFilename, $newPath . '/' . $newName);
unlink($tmpFilename);
return $newName;
}
function CreateDir($dir, $authority = 0755)
{
if (!file_exists($dir)) {
CreateDir(dirname($dir));
mkdir($dir, $authority);
}
return true;
}
$arr = scandir($dir);
$num = count($arr);
$error = './error.txt';
$percent = 0;
foreach ($arr as $k => $v) {
if (!is_numeric($v)) continue;
$filesArr = scandir($dir . '/' . $v);
foreach ($filesArr as $m => $n) {
$_file = $dir . '/' . $v . '/' . $n;
$_newFile = $dir . '/' . $v . 'small';
if ($m == 0 || $m == 1) continue;
$st = imageResize($_file, $_newFile, $n);
if (!$st) {
file_put_contents($error, $_file . PHP_EOL, FILE_APPEND);
}
}
$a = intval($k / $num * 10000) / 100;
if ($a != $percent) {
$percent = $a;
echo $percent . '%' . PHP_EOL;
}
}
还没有评论,来说两句吧...