日期:2014-05-17  浏览次数:20590 次

[散分]生活便利小代码,拍照后,批量递归缩放目录图片.
新入手单反一周了,今天终于找上了机会带上老婆老妈去荔枝公园拍了一天的照,回来准备上传至相册,突然发现,每张图片都有点偏大,找工具也很累,直接上网,东拼西凑了点代码.实现将指定目录的图片,按指定大小范围缩放并输出到指定目录(含递归) ,供自己以后处理相片使用. 不多废话了,附代码.

    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 库代码.

<?php
/**
 * 图片处理助手
 */
class imgHelper
{
    public $srcFiles;     //源文件   array
    public $srcDirs;      //源目录
    public $exportDir;    //输出目录
    public $exportFiles;  //输出文件  array
    private  $_option = array("maxWidth"=>"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)
    {
            //创建目录目录!