php遍历目录图片并显示,php实现遍历目录压缩图片

php实现遍历目录压缩图片,使用php语言遍历目录,查找所有图片并进行压缩,减少图片占用的空间,可以加快页面展示速度,有利于提升整个网站加载速度。

代码如下:<?php

/**

* 遍历目录压缩图片

*/

function zip_img($filename){

$percent = 1;

// 获取新的尺寸

$imginfo = list($width, $height) = getimagesize($filename);

$type = $imginfo['mime'];

$new_width = $width * $percent;

$new_height = $height * $percent;

while($new_width>620 || $new_height>960){

$percent = 0.8;

$new_width = $new_width * $percent;

$new_height = $new_height * $percent;

}

$image_p = imagecreatetruecolor($new_width, $new_height);

if(strpos($type,'png')){

$image = imageCreateFromPng($filename);

//分配颜色 + alpha,将颜色填充到新图上

$alpha = imagecolorallocatealpha($image_p, 0, 0, 0, 127);

imagefill($image_p, 0, 0, $alpha);

imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

imagesavealpha($image_p, true);

imagepng($image_p, $filename,5);  //保存图片名字为:123.png

}else if(strpos($type,'jpeg')){

$image = imagecreatefromjpeg($filename);

imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

imagejpeg($image_p, $filename, 55);//保存图片名字为:123.jpg

}else{

echo '图片类型:'.$type.'暂时不支持压缩!';

}

}

function read_all ($dir){

if(!is_dir($dir)) return false;

$handle = opendir($dir);

if($handle){

while(($fl = readdir($handle)) !== false){

$temp = $dir.DIRECTORY_SEPARATOR.$fl;

if(is_dir($temp) && $fl!='.' && $fl != '..'){

echo '目录:'.$temp.'
';

read_all($temp);

}else{

if($fl!='.' && $fl != '..'){

zip_img($temp);

echo '文件:'.$temp.'
';

}

}

}

}

}

read_all('D:\000\code\WWW\test\yunparse\cache\2017\12-25');

echo '压缩完成'.'
';

?>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值