PHP version of the photos by the date of classification collation source

Source: Internet
Author: User
Tags getmessage sprintf

    • PHP version of the photos by the date of classification collation source
    • Categorize by year-month table of contents
    • Skipping duplicate files
    • Separate classification of video files and non-picture files
    • Photos that can't read a date are categorized separately

<?PHP/*2014/4/1 17:27 klggg Photos by the date of the photo to organize dependent php_exif extension win under open extension extension=php_exif.dll; Note that this paragraph must be placed under Extension=php_mbstring.dll */date_default_timezone_set (' PRC ');//require dirname (__file__). ' /vendor/autoload.php '; $curr _dir_path = DirName (__file__); The photo source path to be processed * need to be modified for your own situation $photo_source_path = ' k:/family photo '; $config = Array (' fileextension ' = = Array (//Image extension ' pic ' =& Gt Array (' jpg ', ' png ', ' gif ', ' BMP '),//Video extension ' movies ' = ' + ' = Array (' mov ', ' 3gp ', ' mp4 ') '), ' path ' = = Array (//All new directory generated root directory, * Notice the change to your path ' root ' and $curr _dir_path. ' /pic_new_month '); $config [' Path '] [' pic '] = $config [' path '] [' root ']. ' /pic ';//which directory the photo is moved to $config[' path ' [' movies '] = $config [' path '] [' root ']. ' /movies ';//the directory where the video was moved $config[' path ' [' unkown '] = $config [' path '] [' root ']. ' /unkown ';//non-photo file to which directory//initialize log related $log_path = $config [' path '] [' root ']. ' /log/'; if (!is_dir ($log _path)) mkdir ($log _path, 0755, true); $log _file = $log _path. ' /'. Date (' y-m-d '). Log '; $log _category = ' photomove '; $log =null; $log _config = Array (' Locking ' =&GT 1, ' buffering ' = True, ' lineformat ' = '%1 $ s%2$s [%3$s]%8$s->%7$s%6$s%4$s '); if (!defined (' Pear_log_debug ')) {     Define (' Pear_log_emerg ', 0);     /* System is unusable */define (' Pear_log_alert ', 1);     /* Immediate action required */define (' Pear_log_crit ', 2);     /* Critical conditions */define (' Pear_log_err ', 3);     /* Error conditions */define (' pear_log_warning ', 4);     /* Warning conditions */define (' Pear_log_notice ', 5);     /* Normal but significant */define (' Pear_log_info ', 6);     /* Informational */define (' Pear_log_debug ', 7); /* Debug-level Messages */$log = Defaultlog::singleton ("File", $log _file, $log _category, $log _config,pear_log_debug);} else{$log = Log::singleton ("File", $log _file, $log _category, $log _config,pear_log_debug);} $PhotoMove _obj= New Photomove ($config, $log); $PhotoMove _obj->run ($photo _source_path); echo "Done"; class Photomove {Private $mRootPath = './tmp ';p rivate $logger = null;private $mConfig = Array ();p ublic function __construct ($config, $logger) {$this->mconfig = $config; $this->mrootpath = $config [' path '] [' Root '];foreach ($ config[' path '] as $tmp _path) {if (!is_dir ($tmp _path)) mkdir ($tmp _path, 0755, true);} $this->logger = $logger;} /** * Run Script entry * @param string $srcPath photo source directory * */public function run ($srcPath) {$it = new Recursivedirectoryiterator ($src Path), foreach (New Recursiveiteratoriterator ($it, 2) as $file _path) {if ($file _path->isdir ()) continue; $file _path_ Name = $file _path->__tostring (); $this->logger->info (' file_path_name: '. $file _path_name); $file _info = PathInfo ($file _path_name); if (' thumbs.db ' = = Strtolower ($file _info[' basename ')) continue;if (!isset ($file _info[') Extension ']) {$this->logger->notice (' No extension: '. $file _path_name); $file _info[' extension '] = ';} $file _info[' extension '] = Strtolower ($file _info[' extension ');//Find picture if (In_array ($file _info[' extension '], $this- >mconfig[' fileextension ' [' pic ']) {$tmp _timestamp = $this->getdatetimeoriginal ($file _path_name);//move to the new directory $new_dir = $this->mconfig[' path ' [' pic ']. ' /'. Date (' Y-m ', $tmp _timestamp), if (!is_dir ($new _dir)) mkdir ($new _dir, 0755, true); $tmp _new_file_path = $new _dir. '/'. $file _info[' basename ']; $this->move ($file _path_name, $tmp _new_file_path);} else if (In_array ($file _info[' extension '), $this->mconfig[' fileextension '] [' movies '])) {$tmp _new_file_path = $ this->mconfig[' path ' [' movies ']. ' /'. $file _info[' basename '); $this->move ($file _path_name, $tmp _new_file_path);} else{//non-image file processing $this->logger->notice (' Not image ': '. $file _path_name); $tmp _new_file_path = $this mconfig[' path ' [' unkown ']. ' /'. $file _info[' basename '; $this->move ($file _path_name, $tmp _new_file_path);}} /** * Take photo date * @param string $filePathName photo full path * @param string $defaultDateTime The default time when the snapshot time is not taken * @return int returns the timestamp * */p ublic function getdatetimeoriginal ($filePathName, $defaultDateTime = ' 1970:01:01 01:01:01 ') {$exif = Exif_read_data ($ Filepathname, 0, true); $date _time_original = $defaultDateTime; if (Empty ($exif [' EXIF ']) | | Empty ($exif [' Exif '] [' datetimeoriginal ']) {$this->logger->warning ("Empty Datetimeoriginal");}    else$date_time_original = $exif [' exif '] [' datetimeoriginal ']; String "2011:03:13 10:23:09" $this->logger->info (' datetimeoriginal: '. $date _time_original); $tmp _ timestamp = Strtotime ($date _time_original); return $tmp _timestamp;}  /** * Move File * @param string $oldFilePath The full path of the original file * @param string $newFilePath destination file full path * @return bool * */public function Move ($oldFilePath, $newFilePath) {//For an existing file if (File_exists ($newFilePath)) {$this->logger->notice ("File_ Exists ". $newFilePath); return false;} $result = false;//if ($result = = Copy ($oldFilePath, $newFilePath)) if ($result = = Rename ($oldFilePath, $newFilePath)) $ This->logger->err ("Rename false, to". $newFilePath); Else$this->logger->info (' [OK] move '. $oldFilePath. ' To '. $newFilePath); return $result;}}  Class Defaultlog {var $_formatmap = array ('%{timestamp} ' = '%1 $ S ', '%{ident} '    = '%2$s ', '%{priority} ' = '%3$s ', '%{message} ' =&gt ;                            '%4$s ', '%{file} ' = '%5$s ', '%{line} ' = '%6$s ',                            '%{function} ' = '%7$s ', '%{class} ' = '%8$s ',    '%\{' = '%%{');    var $_lineformat = '%1 $ s%2$s [%3$s]%4$s ';    var $_timeformat = '%b%d%h:%m:%s ';    var $_eol = "\ n";    var $_dirmode = 0755;private $_filename= './tmp '; var $_backtrace_depth = 0;public function __construct ($name, $ident, $conf, $level = ") {$this->_filename = $na        Me        $this->_ident = $ident;                                             if (!empty ($conf [' LineFormat '])) {$this->_lineformat = Str_replace (Array_keys ($this->_formatmap), Array_values ($this->_formatmap), $con f[' LinefOrmat ']);    }if (!is_dir (dirname ($this->_filename)) {mkdir (dirname ($this->_filename, $this->_dirmode,true));}} public static function Singleton ($handler, $name = ", $ident =", $conf = Array (), $        Level = Pear_log_debug) {static $instances;        if (!isset ($instances)) $instances = Array ();        $signature = Serialize (Array ($handler, $name, $ident, $conf, $level));        if (!isset ($instances [$signature])) {$instances [$signature] = new self ($name, $ident, $conf, $level);    } return $instances [$signature]; } function log ($message, $priority = null) {/* Extract the string representation of the message. */$message        = $this->_extractmessage ($message); /* Build The string containing the complete log line.                               */$line = $this->_format ($this->_lineformat, strftime ($this->_timeformat), $priority, $message). $this->_eol;error_log ($line, 3, $this->_filename); Echo $line;    } function Emerg ($message) {return $this->log ($message, Pear_log_emerg);    } function alert ($message) {return $this->log ($message, Pear_log_alert);    } function Crit ($message) {return $this->log ($message, Pear_log_crit);    } function Err ($message) {return $this->log ($message, Pear_log_err);    } function Warning ($message) {return $this->log ($message, pear_log_warning);    } function Notice ($message) {return $this->log ($message, Pear_log_notice);    } function info ($message) {return $this->log ($message, pear_log_info);    } function Debug ($message) {return $this->log ($message, pear_log_debug); } function _extractmessage ($message) {/* * * If we ' ve been given an object, attempt to extract the Mes  Sage using * a known method. If we can ' t find such a method, DEfault to the * "human-readable" version of the object.         * * We also use the human-readable format for arrays. */if (Is_object ($message)) {if (Method_exists ($message, ' getmessage ')) {$message = $me            Ssage->getmessage ();            } else if (Method_exists ($message, ' tostring ')) {$message = $message->tostring ();            } else if (Method_exists ($message, ' __tostring ')) {$message = (string) $message;            } else {$message = Var_export ($message, true); }} else if (Is_array ($message)) {if (Isset ($message [' message '])) {if (Is_scalar ($messa                ge[' message ')) {$message = $message [' message '];                } else {$message = Var_export ($message [' message '], true);            }} else {$message = Var_export ($message, true); }} else if (is_bool ($message) | |        $message = = = NULL) {$message = Var_export ($message, true); }/* Otherwise, we assume the message is a string.    */return $message; } function _format ($format, $timestamp, $priority, $message) {/* * If The format string references a         NY of the Backtrace-driven * variables (% 5%6,%7,%8), generate the BackTrace and fetch them.            */if (Preg_match ('/%[5678]/', $format)) {/* Plus 2 to account for our internal function calls. */            $d = $this->_backtrace_depth + 2;        List ($file, $line, $func, $class) = $this->_getbacktracevars ($d);  }/* Build the formatted string. We Use the sprintf () function ' s * "argument swapping" capability to dynamically select and position * the         Variables which would ultimately appear in the log string. */Return sprintf ($format, $timestamp, $tHis->_ident, $this->prioritytostring ($priority), $message, Isset ($file)? $file: ", Isset ($line)? $line: ", Isset ($func)? $func: ", Isset ($class)?    $class: ");            } function prioritytostring ($priority) {$levels = array (Pear_log_emerg = = ' Emergency ', Pear_log_alert = ' ALERT ', Pear_log_crit = ' critical ', Pear_log_err = ' er    Ror ', pear_log_warning = ' WARNING ', Pear_log_notice = ' NOTICE ', pear_log_info        = ' Info ', pear_log_debug = ' DEBUG ');    return $levels [$priority];        } function _getbacktracevars ($depth) {/* Start by generating a backtrace from the ' current ' call. */        $BT = Debug_backtrace (); /* Store Some handy shortcuts to our previous frames.    */    $BT 0 = isset ($bt [$depth])?        $BT [$depth]: null; $BT 1 = isset ($BT [$depth + 1])?        $BT [$depth + 1]: null; /* * If We were ultimately invoked by the composite handler, we need to * increase our depth one Additiona         L level to compensate. */$class = isset ($bt 1[' class ')?        $BT 1[' class '): null;            if ($class!== null && strcasecmp ($class, ' log_composite ') = = 0) {$depth + +; $BT 0 = isset ($bt [$depth])?            $BT [$depth]: null; $BT 1 = isset ($BT [$depth + 1])?            $BT [$depth + 1]: null; $class = isset ($bt 1[' class ')?        $BT 1[' class '): null; }/* * we ' re interested in the frame which invoked the log () function, so * we need to walk back so  Me number of frames into the backtrace.   The * $depth parameter tells us where to start looking. We Go one step * further back to find the name of the encapsulating function from * which log () is called        . */$file = Isset ($bt 0)?        $BT 0[' file ']: null; $line = Isset ($bt 0)?        $BT 0[' line ': 0; $func = Isset ($bt 1)?        $BT 1[' function ']: null; /* * However, if log () is called from one of our "shortcut" functions, * we ' re going-need to go-back a         N Additional step.  */if (In_array ($func, Array (' Emerg ', ' alert ', ' crit ', ' err ', ' warning ', ' notice ',            ' Info ', ' Debug ')) {$BT 2 = isset ($BT [$depth + 2])? $BT [$depth + 2]: null; $file = Is_array ($bt 1)?            $BT 1[' file ']: null; $line = Is_array ($bt 1)?            $BT 1[' line ': 0; $func = Is_array ($bt 2)?            $BT 2[' function ']: null; $class = isset ($bt 2[' class ')?        $BT 2[' class '): null; }/* * If We couldn ' t extract a function name (perhaps because we were * executed from the "main" C         Ontext), provide a default value.        */if ($func = = = null) {$func = ' (none) '; }       /* Return a 4-tuple containing (file, line, function, Class).    */return Array ($file, $line, $func, $class); }}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.