访问路径或者api接口调用
public function index(){
$dir = 'uploads';//指定本地目录
$namefis = [];
$username = my_dir($dir);//遍历后目录结果,这是一个多维数组
foreach ($username as $k => $v) {
foreach ($v as $k1 => $v1) {
$namefis[] = 'uploads/' . $k . '/' . $v1;
// compressedImage('uploads/' . $k . '/' . $v1, 'uploads/' . $k . '/' . $v1,60);
}
}
dump($namefis);//查看输出的是不是图片路径。是的话,compressedImage,方法。压缩到60的质量,压缩之前,记得备份下,不然压缩的太狠,就没原图了。
// return $this->fetch();
}
dump 结果查看uploads目录
![](https://img2020.cnblogs.com/blog/735218/202009/735218-20200925000520152-1535406742.png)
两个经典函数
function my_dir($dir) {
$files = array();
if(@$handle = opendir($dir)) { //注意这里要加一个@,不然会有warning错误提示:)
while(($file = readdir($handle)) !== false) {
if($file != ".." && $file != ".") { //排除根目录;
if(is_dir($dir."/".$file)) { //如果是子文件夹,就进行递归
$files[$file] = my_dir($dir."/".$file);
} else { //不然就将文件的名字存入数组;
$files[] = $file;
}
}
}
closedir($handle);
return $files;
}
}
function compressedImage($imgsrc, $imgdst,$per=60)
{
list($width, $height, $type) = getimagesize($imgsrc);
$new_width = $width;//压缩后的图片宽
$new_height = $height;//压缩后的图片高
switch ($type) {
case 1:
$giftype = check_gifcartoon($imgsrc);
if ($giftype) {
header('Content-Type:image/gif');
$image_wp = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromgif($imgsrc);
imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); //90代表的是质量、压缩图片容量大小
imagejpeg($image_wp,$imgdst,$per);
imagedestroy($image_wp);
imagedestroy($image);
}
break;
case 2:
header('Content-Type:image/jpeg');
$image_wp = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($imgsrc);
imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); //90代表的是质量、压缩图片容量大小
imagejpeg($image_wp, $imgdst, $per);
imagedestroy($image_wp);
imagedestroy($image);
break;
case 3:
header('Content-Type:image/png');
$image_wp = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefrompng($imgsrc);
imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); //90代表的是质量、压缩图片容量大小
imagejpeg($image_wp, $imgdst, $per);
imagedestroy($image_wp);
imagedestroy($image);
break;
}
}