[散分]生活便利小代码,拍照后,批量递归缩放目录图片.
新入手单反一周了,今天终于找上了机会带上老婆老妈去荔枝公园拍了一天的照,回来准备上传至相册,突然发现,每张图片都有点偏大,找工具也很累,直接上网,东拼西凑了点代码.实现将指定目录的图片,按指定大小范围缩放并输出到指定目录(含递归) ,供自己以后处理相片使用. 不多废话了,附代码.
<br /> header('Content-type:text/html; charset=utf-8');<br /> require "lib/imgHelper.php";<br /> $imgHelper = new imgHelper( "dir1" );<br /> $imgHelper->setOutputDir( "dir2" );<br /> //默认输出在1024 768 下等比缩放,需要自定义时,$imgHelper->setOutputSize(1440,900);<br /> $imgHelper->execution();<br />
<br> <?php <br /> /**<br> * 图片处理助手<br> */<br> class imgHelper<br> {<br> public $srcFiles; //源文件 array<br> public $srcDirs; //源目录<br> public $exportDir; //输出目录<br> public $exportFiles; //输出文件 array<br> private $_option = array("maxWidth"=>"1024" , "maxHeight"=>"768");<br> <br> function __construct($dir = '' , $option = array() )<br> {<br> if (!$dir) return;<br> $this->srcDirs = $dir;<br> $this->srcFiles = $this->traversal($dir);<br> $this->setOptions( $option );<br> }<br> <br> /**<br> * 设置输出目录<br> * @param $dir<br> */<br> public function setOutputDir( $dir )<br> {<br> if( !is_dir( $dir )) { mkdir($dir , 0777 , 1);}<br> $this->exportDir = $dir;<br> }<br> <br> public function execution()<br> {<br> foreach( $this->srcFiles as $key =>$val ):<br> $srcImg = $val;<br> $toFile = str_replace( $this->srcDirs , $this->exportDir , $srcImg); //todo 简便处理.<br> $maxWidth = $this->_option["maxWidth"];<br> $maxHeight = $this->_option["maxHeight"];<br> $this->resize($srcImg , $toFile , $maxWidth , $maxHeight );<br> endforeach;<br> }<br> <br> //缩放图片.<br> private function resize($srcImage,$toFile,$maxWidth = 100,$maxHeight = 100,$imgQuality=100)<br> {<br> //创建目录目录!<br> $pInfo = pathinfo( $toFile );<br> $dir = $pInfo["dirname"]; if(!is_dir( $dir) ){ mkdir($dir , 0777 , 1);} <div class="clear"> </div>