[散分]生活便利小代码,拍照后,批量递归缩放目录图片.
程序员文章站
2024-01-20 22:52:46
...
新入手单反一周了,今天终于找上了机会带上老婆老妈去荔枝公园拍了一天的照,回来准备上传至相册,突然发现,每张图片都有点偏大,找工具也很累,直接上网,东拼西凑了点代码.实现将指定目录的图片,按指定大小范围缩放并输出到指定目录(含递归) ,供自己以后处理相片使用. 不多废话了,附代码.
lib 库代码.
header('Content-type:text/html; charset=utf-8'); require "lib/imgHelper.php"; $imgHelper = new imgHelper( "dir1" ); $imgHelper->setOutputDir( "dir2" ); //默认输出在1024 768 下等比缩放,需要自定义时,$imgHelper->setOutputSize(1440,900); $imgHelper->execution();
lib 库代码.
"1024" , "maxHeight"=>"768"); function __construct($dir = '' , $option = array() ) { if (!$dir) return; $this->srcDirs = $dir; $this->srcFiles = $this->traversal($dir); $this->setOptions( $option ); } /** * 设置输出目录 * @param $dir */ public function setOutputDir( $dir ) { if( !is_dir( $dir )) { mkdir($dir , 0777 , 1);} $this->exportDir = $dir; } public function execution() { foreach( $this->srcFiles as $key =>$val ): $srcImg = $val; $toFile = str_replace( $this->srcDirs , $this->exportDir , $srcImg); //todo 简便处理. $maxWidth = $this->_option["maxWidth"]; $maxHeight = $this->_option["maxHeight"]; $this->resize($srcImg , $toFile , $maxWidth , $maxHeight ); endforeach; } //缩放图片. private function resize($srcImage,$toFile,$maxWidth = 100,$maxHeight = 100,$imgQuality=100) { //创建目录目录! $pInfo = pathinfo( $toFile ); $dir = $pInfo["dirname"]; if(!is_dir( $dir) ){ mkdir($dir , 0777 , 1);} list($width, $height, $type, $attr) = getimagesize($srcImage); if($width "$width" , "maxHeight"=>"$height"); $this->setOptions( $_option ); } /** * 设置可选参数 * @param $option */ private function setOptions( $option) { foreach( $option as $key =>$val): if( isset( $option[$key]) && $option[$key] ){ $this->_option[$key] = $val; } endforeach; } /** * 遍得到文件夹下的所有文件 */ private function traversal($path) { if (!$path) return array(); $files = array(); if (!is_dir($path)) return; foreach (scandir($path) as $file) { if ($file != '.' && $file != '..') { $path2 = $path . '/' . $file; if (is_dir($path2)) { $temp = $this->traversal($path2); $files = array_merge($files, $temp); } else { if ($this->isIMg($file)) { $files[] = $path . "/" . $file; } } } } return $files; } /** * 判断是否是图片 * @param $file * @return bool */ private function isIMg($file) { $pInfo = pathinfo( $file); $extention = $pInfo["extension"]; return preg_match("/(jpg)|(png)|gif/i" , $extention); } /** * 调试数据 */ public function debug() {$this->pr($this->srcFiles, "待处理图片数组."); $this->pr( $this->srcDirs , "源目录"); $this->pr( $this->exportDir , "目标目录"); } private function pr($array, $title = 'DEBUG', $type = 'array', $width = '') { /*** @格式化输出 */ $title .= date("Y-m-d H:i:s"); $widthStr = ""; if ($width) $widthStr = "width:$width" . "px"; echo "