renrot-1.1/000755 001751 000024 00000000000 11072426531 013012 5ustar00zeusstaff000000 000000 renrot-1.1/README.russian000644 001751 000024 00000003244 11072426514 015361 0ustar00zeusstaff000000 000000 О ПРОГРАММЕ RenRot переименовывает файлы в соответствие с EXIF-тегами DateTimeOriginal и FileModifyDate, если они присутствуют, иначе, имя устанавливается в соответствие с текущими датой и временем. Дополнительно изображение восстанавливается в ориентации по тегу Orientation. Скрипт также может добавлять комментарии в теги Commentary и UserComment. Возможна установка персональной информации через XMP-теги, определённые в конфигурационном файле. Также с версии 0.16.2 внедрена функция агрегации, подразумевающая перенесение файлов из рабочего каталога в подкаталоги согласно шаблону, определяемому из частей даты и времени создания фото. В командной строке можно задать набор файлов, вместо целого каталога. Установка атрибута mtime включена по умолчанию. Более подробно о программе можно узнать из англоязычной документации README и renrot(1). ВОПРОСЫ Возникшие замечания, вопросы и предложения, пожалуйста, направляйте авторам, адреса которых указаны в файле AUTHORS. renrot-1.1/MANIFEST000644 001751 000024 00000001626 11072426531 014150 0ustar00zeusstaff000000 000000 AUTHORS ChangeLog Makefile.PL MANIFEST This file NEWS User friendly change log README README.russian Small description for russians users README.Windows Installation instructions for windows users renrot RenRot script renrot.spec RPM spec file TODO etc/colors.conf Colorization scheme etc/copyright.tag Text to put to Copyright tag etc/renrot.conf Sample of configuration file etc/tags.conf Strings to fill appropriate tags sample/dotkeywords Sample of a .keywords file sample/dotrank Sample of a .rank file META.yml Module meta-data (added by MakeMaker) renrot-1.1/TODO000644 001751 000024 00000004776 11072426514 013521 0ustar00zeusstaff000000 000000 TODO SEMANTICS - not yet +- partialy done + already done ? needs to be checked q optional feature BUGS - make possible to use same EXIF tags in different groups EXIF tags q to write to some tag the options passed to renrot +- to implement %t in name template, where the array of desired tags will be inited PLUGINS - plugin interface implementation (EXIF data transfer variant) - print some text on image (i.e. date and timestamp) [guess perl-GD will be optional requrement] - special effects (thumbnail layering over the image e.t.c.) - jpgfromraw +- index page (from thumbnailimages) - shrinking e.t.c. - image hystogramm creation q split EXIF -> xml, to extract EXIF data from file original to the separate files and to clear EXIF data from files originals Performance - to implement --no-rename option ... - decrease disk IO operations as possible +- to implement possibility to work with other formats, which use EXIF mechanism (conversions by ImageMagick and/or netpbm as well as jpegtran) +- implement aggregation option (to aggregate large bundle of files according the different time intervals, perhaps with some kind of euristics for analyzing the bigest time interval between shots) - to fix the feature with --aggr-template SOMENAME, when SOMENAME is dumb name, no % character and than renrot moves all to SOMENAME directory it'll be called OUTDIR - to implement possibility to work with several IN directories and to output to the set of OUT directories - avoid hard link making where in and out files on different partitions - check free space before start batch operation (probably find given file with maximum lenght and compare it with 1/3 of free space or 1/2 if --no-backup is defined) - Use convert instead of jpegtran or vice versa (optional) User interface - GUI on PerlTk (due to WinCE hasn't real console) with some additional functions such as keywordizer - to implement help output by topics (sole -h outputs list of topics like rename,rotate,keyword e.t.c. and -h keyword outputs help for keyword related q integration with gallery File naming q virtual renaming Verbosity q to implement progress indicator or spinning indicator Code +- to review the code to optimize it where it's possible. +- to tune style look of comments, code, e.t.c. - Find way to update ChangeLog in automatic manner Other - to implement --include-file option (andy) - UTF8fy (comments, tags, ...) since it's not implemented in ExifTool yet renrot-1.1/README.Windows000644 001751 000024 00000007077 11072426514 015337 0ustar00zeusstaff000000 000000 INSTALLATION You can install RenRot to your Windows platform, but you need to do several extra steps. STEP 1 First off, you must have a Perl 5.6.0 or later available on your system. If you need to install one, ActivePerl can be a good choice. You can get it here http://www.activestate.com/Products/ActivePerl/ Currently you don't have to provide any personal info for download, but if you are still in doubt, you can try to follow direct link http://www.activestate.com/Products/Download/Download.plex?id=ActivePerl and choose a build for Windows (as msi package - clickable option for novice, or zip file for more experienced users). Once you have Perl installed (it goes to C:\Perl by default), you can type perl --version to see installed version. STEP 2.1 Now you need make/nmake to continue. You can skip this step if you have installed MS Visual Studio. The next article http://johnbokma.com/perl/make-for-windows.html explains what to do and what to make, but shortly go to Microsoft's Q132084 http://support.microsoft.com/default.aspx?scid=kb;en-us;Q132084 and download nmake http://download.microsoft.com/download/vc15/patch/1.52/w95/en-us/nmake15.exe Run the downloaded file to extract it and copy both the NMAKE.EXE and the NMAKE.ERR files to your Perl bin directory, normally C:\Perl\bin. STEP 2.2 In case to get functionality of Contact Sheet Generator, you'll need ImageMagick pakage. Download it from: http://www.imagemagick.org/script/binary-releases.php#windows In installation menu choose "With PerlMagick"! STEP 3 Now download all dependencies (like ExifTool), unpack and install them, using nmake command instead of make. Use cpan for needed modules like running (automatic mode) cpan Image::ExifTool or by cpan shell starting with (manual mode) perl -MCPAN -e shell STEP 4 Just like you installed dependencies, you can install renrot now: perl Makefile.PL nmake nmake install You are ready to go! NOTES: 1. To unpack tar.gz-files you can use WinZip (make sure that you extract files including full path, especially for ExifTool), or use free utility 7-zip http://www.7-zip.org/ 2. Be sure to call NMake.exe instead of make command. 3. One of the dependencies is jpegtran from libjpeg library and they do not provide binaries for Windows platform. To be able to rotate images, you must build it from source code yourself or download from this site http://sylvana.net/jpegcrop/jpegtran/ 4. Use double quotes instead of single in command line for disabling misinterpretation of arguments. 5. Read contact sheet related section in renrot manual and renrot.conf file for font choosing. INSTALL TO PDA (EXPERIMENTAL AND UNDER DEVELOPMENT, MAY NOT WORK) Installation process for a WinCE devices is not trivial. Please, be accurate when you make installation. Using renrot and exiftool scripts on PDA is useful for device that has built-in camera such as FSC Pocket Loox 720. First, you need to install Perl and Image::ExifTool to Pocket PC or another PDA. Visit the following site and get the lastest perl distribution according to platform (usually ARM for Pocket PC): http://perlce.sf.net There you can found detailed installation instructions for perl. Also we recommends to install the PerlIDE GUI that helps with scripting very much. Second, additional modules should be installed for starting ExifTool: File::RandomAccess Simple way to install is a copy their as-is from your PC perl distribution to the %perllib% on PDA. RenRot and ExifTool's several functions are not working now due to precompiled perl does not contain strftime(). renrot-1.1/sample/000755 001751 000024 00000000000 11072426531 014273 5ustar00zeusstaff000000 000000 renrot-1.1/etc/000755 001751 000024 00000000000 11072426531 013565 5ustar00zeusstaff000000 000000 renrot-1.1/renrot000755 001751 000024 00000303626 11072426514 014264 0ustar00zeusstaff000000 000000 #!/usr/bin/env perl # # vim: ts=2 sw=2 et : # # Analyze crash in third-party modules # (Receipt has been taken from http://ilya-dogolazky.livejournal.com/15061.html) BEGIN { $| = 1; $SIG{__DIE__} = sub { use Carp; confess $_[0] . 'Aborted' } } use strict; use warnings; use diagnostics; require 5.006; use Time::localtime; use Time::Local; use Image::ExifTool; use Getopt::Long; use File::Spec; use File::Path; use Term::ANSIColor; $Term::ANSIColor::AUTORESET = 1; $Term::ANSIColor::EACHLINE = "\n"; $ENV{ANSI_COLORS_DISABLED} = 1; # perl 5.8.x memory overflow workaround (perl5.8.1-8 which uses it's own malloc) my $mem_trouble_stub = " "x4_000_000; undef $mem_trouble_stub; # Versioning my @svnrevision = split(/ /, '$Revision: 578 $'); our $VERSION = '1.1'; # the version of this script our $REVISION = $svnrevision[1]; # revision my $maxVerbosity = 4; # our max verbosity level (internal) my $homeURL = 'http://puszcza.gnu.org.ua/projects/renrot/'; # homepage of the project ######################################################################################## # # The global definition for a new XMP namespace. The # %Image::ExifTool::UserDefined::RenRot defines XMP-RenRot tags which could be # added to mark the file as processed with RenRot. # if (defined %Image::ExifTool::UserDefined::RenRot) { fatalmsg ("Won't redefine Image::ExifTool::UserDefined::RenRot.\n"), die_renrot(); } %Image::ExifTool::UserDefined::RenRot = ( GROUPS => { 0 => 'XMP', 1 => 'RenRot', 2 => 'Image' }, NAMESPACE => [ 'RenRot' => $homeURL ], WRITABLE => 'string', RenRotFileNameOriginal => { }, RenRotProcessingTimestamp => { }, RenRotVersion => { }, RenRotURL => { }, ); # The %Image::ExifTool::UserDefined hash defines new tags to be added to # existing tables. %Image::ExifTool::UserDefined = ( # new XMP namespaces must be added to the Main XMP table 'Image::ExifTool::XMP::Main' => { RenRot => { SubDirectory => { TagTable => 'Image::ExifTool::UserDefined::RenRot', }, }, }, ); ######################################################################################## # # Parsed configuration file in hash # my %cfgOpts = ( 'aggregation delta' => 900, 'aggregation directory' => 'Images', 'aggregation mode' => 'none', 'aggregation template' => '%Y%m%d', 'aggregation virtual' => 0, 'keywordize' => 0, 'keywords file' => '.keywords', 'keywords replace' => 0, 'mtime' => 1, 'name template' => '%Y%m%d%H%M%S', 'trim' => 1, 'use color' => 0, 'use ipc' => 0, 'contact sheet' => 0, 'contact sheet tile' => '7x5', 'contact sheet title' => 'Default Contact Sheet Title', 'contact sheet dir' => 'Contact.Sheet', 'contact sheet file' => 'cs-%c.jpg', 'contact sheet background' => 'FFF', 'contact sheet bordercolor' => 'DDD', 'contact sheet mattecolor' => 'CCC', 'contact sheet fill' => '000', 'contact sheet font' => 'Helvetica', 'contact sheet label' => '%t', 'contact sheet frame' => '3', 'contact sheet pointsize' => '11', 'contact sheet shadow' => 1, 'contact sheet thm font' => 'Helvetica', 'contact sheet thm fill' => 'gray34', 'contact sheet thm grad fr' => 'FFFFFF', 'contact sheet thm grad to' => '909090', 'contact sheet thm text' => "thumbnail\n\nNA", 'contact sheet rank' => 0, 'contact sheet rank file' => '.rank', 'generate thumbnail size' => '160x120', ); ######################################################################################## # # Command line options # my $aggrDelta; # aggregation time delta in seconds (file with delta > $aggrDelta is placed in new DIR) my $aggrDir; # counterless directory name for "delta" type aggregation my $aggrMode; # define aggregation mode, possible values are: none, delta or template my $aggrTemplate; # template for the files aggregation taken from CLI my $aggrVirtual; # flag to do links instead real file moving while aggregation my $backup = 1; # make or not a backup of the original files my $comfile; # file with commentary my $configFile; # configuration file my $contactSheet; # contact sheet generation my $contactSheetTile; # tile in the montage my $contactSheetTitle; # title for the montage my $contactSheetFile; # file name for the montage my $contactSheetDir; # tmp directory for the montage operations my $contactSheetThm = 0;# is $extToProcess files are the thumbnails? my $contactSheetBg; # background, look ImageMagick documentation for montage options my $contactSheetBd; # bordercolor, look ImageMagick documentation for montage options my $contactSheetMt; # mattecolor, look ImageMagick documentation for montage options my $contactSheetLb; # label, look ImageMagick documentation for montage options my $contactSheetFn; # font, look ImageMagick documentation for montage options my $contactSheetFl; # fill, look ImageMagick documentation for montage options my $contactSheetFr; # frame, look ImageMagick documentation for montage options my $contactSheetPntSz; # pointsize, look ImageMagick documentation for montage options my $contactSheetShadow; # shadow, look ImageMagick documentation for montage options my $contactSheetThmFn; # font, look ImageMagick documentation for montage options my $contactSheetThmFl; # fill, look ImageMagick documentation for montage options my $contactSheetThmGrFr;# thumbnail background gradient from my $contactSheetThmGrTo;# thumbnail background gradient to my $contactSheetThmText;# thumbnail text my $contactSheetRank; # ranking my $contactSheetRankFile; # file with images ranks my $countFF = 1; # use fixed field for counter my $countStart = 1; # Start value for counter my $countStep = 1; # Step for counter my $dryRun = 0; # show what would have been happened my @excludeList = (); # files that will be excluded from list my $extToProcess = ''; # the extension of files to work with my $gen_thm = 0; # to not to generate ThumbnailImage if empty my $keywordize; # keywordize or not my $keywordsReplace; # whether to add keywords to the existent ones or replace them my $keywordsFile; # file with keyword set my $mtime; # mtime taken from CLI my $nameTemplate; # template for the filename taken from CLI my $noRename = 0; # no rename needed, default is to rename to the YYYYmmddHHMMSS.ext my $noRotation = 0; # no rotation needed, default is to rotate my $noTags = 0; # no tags writing needed my $noRenRoTagMtm = 0; # no rename, no rotate, no tag and no mtime have to be done my $orientTag = 0; # rotate by changing Orientation tag (no real rotation) my $quiet = 0; # suppressing messages my $rotateAngle; # define the angle to rotate on 90, 180 or 270 my $rotateThumbnail; # define the angle to rotate on 90, 180 or 270 my $subFileSet = ''; # subset of files to process, given in file rather than in commandline my %tagsFromCli = (); # tags are got from CLI my @tag_to_name = (); # tags for name building, theirs values to be used (in theory any EXIF) my $trim; # jpegtran -trim my $useColor; # colorized output my $useIPC; # rotate thumbnail via pipe my $userComment; # text to put into UserComment tag my $verbose = 0; # verbosity of output my $workDir = './'; # we'll work ONLY in current directory my $isThereIM = 0; # is there Image::Magick package? ######################################################################################## # # Tags hash for injecting to EXIFs when renaming # my %tags = ( 'RenRotProcessingTimestamp' => { value => timeNow(), group => 'RenRot', }, 'RenRotVersion' => { value => $VERSION . " (r" . $REVISION . ")", group => 'RenRot', }, 'RenRotURL' => { value => $homeURL, group => 'RenRot', }, ); # define tags for filling ######################################################################################## # # Global variables (internal) # my @rotparms = ( '', '-flip horizontal', '-rotate 180', '-flip vertical', '-transpose', '-rotate 90', '-transverse', '-rotate 270', ); # jpegtran options array to rotate the file my @angles = ( '', 'fh', '180cw', 'fv', 'tp', '90cw', 'tv', '270cw', ); # the array of suffixes to add to the newfilename after rotating my %rotangles = ( '90' => '-rotate 90', '180' => '-rotate 180', '270' => '-rotate 270' ); # array of options to rotate file "by hands" my %rotorient = ( 1 => 0, 6 => 90, 3 => 180, 8 => 270, ); my %rotorientrev = reverse %rotorient; my %incFiles = (); # hash of included files while parsing configuration file my @multOpts = ( 'color', 'include', 'tag', 'tagfile', ); my @files = (); # array of the sorted filenames to process my %filenameshash = (); # hash for old file names ######################################################################################## # # Colors hash # my %colors = ( debug => {value => 'green'}, error => {value => 'magenta'}, fatal => {value => 'red'}, info => {value => 'bold'}, process => {value => 'white'}, warning => {value => 'cyan'}, ); # Prints colored message to STDERR sub printColored { my $facility = shift; if ($cfgOpts{'use color'} != 0) { if (defined $facility and defined $colors{$facility}) { # Put process and info messages to StdOut, otherwise to StdErr if ($facility eq "process" or $facility eq "info") { print STDOUT colored [$colors{$facility}{value}], @_; } else { print STDERR colored [$colors{$facility}{value}], @_; } return; } } # fallback to normal print if ($facility eq "process" or $facility eq "info") { print STDOUT @_; } else { print STDERR @_; } } # general processing message sub procmsg { printColored('process', @_) if ($quiet == 0); } # information message sub infomsg { printColored('info', @_); } # warning message sub warnmsg { printColored('warning', "Warning: ", @_); } # error message sub errmsg { printColored('error', "ERROR: ", @_); } # fatal message sub fatalmsg { printColored('fatal', "FATAL: ", @_); } # debug message sub dbgmsg { my $level = shift; if ($verbose >= $level) { # caller() described in Perl Cookbook 10.4 my $funcname = (caller(1))[3]; $funcname = 'main' if (not defined $funcname); printColored('debug', "DEBUG[$level]: ", $funcname, "(): ", @_); } } ######################################################################################## # Usage : ldbg3($msg, ...) # Purpose : prints debug message on level 3 with EOL # Returns : nothing # Parameters : text message without end of line # Throws : no exceptions # Comments : useful to print command line or configuration option parameters # See Also : dbgmsg() sub ldbg3 { if ($verbose >= 3) { # caller() described in Perl Cookbook 10.4 my $funcname = (caller(1))[3]; $funcname = 'main' if (not defined $funcname); printColored('debug', "DEBUG[3]: ", $funcname, "(): ", @_, "\n"); } }; ######################################################################################## # Usage : die_renrot() # Purpose : dies differently depend on verbose level # Returns : nothing # Parameters : nothing # Throws : no exceptions # Comments : pretty output when die with verbose level is zero # See Also : n/a sub die_renrot { if ($verbose > 0) { die("Fatal"); } exit 127; } ######################################################################################## # Usage : boolConv($var) # Purpose : converts boolean value to human readable string # Returns : string "Yes" or "No" # Parameters : 0 or 1 # Throws : no exceptions # Comments : none # See Also : boolConverter() sub boolConv { my $var = shift; if ($var == 0) { return "No"; } else { return "Yes"; } } ######################################################################################## # Usage : boolConverter($var) # Purpose : converts given string to a boolean value # Returns : number 1 or 0 # Parameters : one of "1", "Yes", "True", "On", "0", "No", "False" or "Off" # Throws : no exceptions # Comments : none # See Also : boolConv() sub boolConverter { my $value = shift; if ($value =~ m/^(0|No|False|Off)$/i) { return 0; } elsif ($value =~ m/^(1|Yes|True|On)$/i) { return 1; } return $value; } ######################################################################################## # Usage : isTherePackage($pkg) # Purpose : checks availability of given package (renrot could be depend of it) # Returns : nothing in case the package available and undef if not # Parameters : $pkg - string with package name # Throws : no exceptions # Comments : none # See Also : n/a sub isTherePackage { my $pkg = shift; return undef unless eval "require $pkg"; } ######################################################################################## # Usage : getOptions(...) # Purpose : parses command line arguments # Returns : nothing # Parameters : many of them, look bellow # Throws : no exceptions # Comments : none # See Also : Getopt::Long GetOptions() sub getOptions { my $showVersion = 0; # need version my $showHelp = 0; # need help my @tmpTags = (); my $getOptions = GetOptions ( "aggr-delta=i" => \$aggrDelta, "aggr-directory=s" => \$aggrDir, "aggr-mode=s" => \$aggrMode, "aggr-template|a=s" => \$aggrTemplate, "aggr-virtual!" => \$aggrVirtual, "backup!" => \$backup, "comment-file=s" => \$comfile, "config-file|c=s" => \$configFile, "contact-sheet|cs!" => \$contactSheet, "contact-sheet-tile|cs-tile=s" => \$contactSheetTile, "contact-sheet-title|cs-title=s" => \$contactSheetTitle, "contact-sheet-file|cs-file=s" => \$contactSheetFile, "contact-sheet-dir|cs-dir=s" => \$contactSheetDir, "contact-sheet-thm|cs-thm" => \$contactSheetThm, "contact-sheet-bg|cs-bg=s" => \$contactSheetBg, "contact-sheet-bd|cs-bd=s" => \$contactSheetBd, "contact-sheet-mt|cs-mt=s" => \$contactSheetMt, "contact-sheet-fl|cs-fl=s" => \$contactSheetFl, "contact-sheet-fn|cs-fn=s" => \$contactSheetFn, "contact-sheet-lb|cs-lb=s" => \$contactSheetLb, "contact-sheet-fr|cs-fr=s" => \$contactSheetFr, "contact-sheet-pntsz|cs-pntsz=i" => \$contactSheetPntSz, "contact-sheet-shadow|cs-shadow" => \$contactSheetShadow, "contact-sheet-thm-fl|cs-thm-fl=s" => \$contactSheetThmFl, "contact-sheet-thm-fn|cs-thm-fn=s" => \$contactSheetThmFn, "contact-sheet-thm-grfr|cs-thm-grfr=s" => \$contactSheetThmGrFr, "contact-sheet-thm-grto|cs-thm-grto=s" => \$contactSheetThmGrTo, "contact-sheet-thm-text|cs-thm-text=s" => \$contactSheetThmText, "contact-sheet-rank|cs-rank!" => \$contactSheetRank, "contact-sheet-rank-file|cs-rank-file=s" => \$contactSheetRankFile, "counter-fixed-field!" => \$countFF, "counter-start=i" => \$countStart, "counter-step=i" => \$countStep, "dry-run" => \$dryRun, "exclude=s" => \@excludeList, "extension|e=s" => \$extToProcess, "generate-thumb|g" => \$gen_thm, "help|?" => \$showHelp, "keywordize!" => \$keywordize, "keywords-file|k=s" => \$keywordsFile, "keywords-replace!" => \$keywordsReplace, "mtime!" => \$mtime, "name-template|n=s" => \$nameTemplate, "no-rename|norename" => \$noRename, "no-rotate|norotate" => \$noRotation, "no-tags|notags" => \$noTags, "no-renrot|nochg" => \$noRenRoTagMtm, "only-orientation" => \$orientTag, "quiet|q" => \$quiet, "rotate-angle|r=i" => \$rotateAngle, "rotate-thumb=i" => \$rotateThumbnail, "sub-fileset=s" => \$subFileSet, "tag|t=s" => \@tmpTags, "trim!" => \$trim, "use-color!" => \$useColor, "use-ipc!" => \$useIPC, "user-comment=s" => \$userComment, "v+" => \$verbose, "version" => \$showVersion, "work-directory|d=s" => \$workDir, ); my $fileCount = scalar(@ARGV); ldbg3("--aggr-delta: $aggrDelta") if (defined $aggrDelta); ldbg3("--aggr-directory: $aggrDir") if (defined $aggrDir); ldbg3("--aggr-mode: $aggrMode") if (defined $aggrMode); ldbg3("--aggr-template: $aggrTemplate") if (defined $aggrTemplate); ldbg3("--aggr-virtual: ", boolConv($aggrVirtual)) if (defined $aggrVirtual); ldbg3("--backup: ", boolConv($backup)); ldbg3("--comment-file: $comfile") if (defined $comfile); ldbg3("--config-file: $configFile") if (defined $configFile); ldbg3("--contact-sheet: ", boolConv($contactSheet)) if (defined $contactSheet); ldbg3("--contact-sheet-tile: $contactSheetTile") if (defined $contactSheetTile); ldbg3("--contact-sheet-title: $contactSheetTitle") if (defined $contactSheetTitle); ldbg3("--contact-sheet-file: $contactSheetFile") if (defined $contactSheetFile); ldbg3("--contact-sheet-dir: $contactSheetDir") if (defined $contactSheetDir); ldbg3("--generate-thumb: ", boolConv($gen_thm)); ldbg3("--contact-sheet-thm: ", boolConv($contactSheetThm)); ldbg3("--contact-sheet-bg: $contactSheetBg") if (defined $contactSheetBg); ldbg3("--contact-sheet-bd: $contactSheetBd") if (defined $contactSheetBd); ldbg3("--contact-sheet-mt: $contactSheetMt") if (defined $contactSheetMt); ldbg3("--contact-sheet-fn: $contactSheetFn") if (defined $contactSheetFn); ldbg3("--contact-sheet-lb: $contactSheetLb") if (defined $contactSheetLb); ldbg3("--contact-sheet-fr: $contactSheetFr") if (defined $contactSheetFr); ldbg3("--contact-sheet-rank: ", boolConv($contactSheetRank)) if (defined $contactSheetRank); ldbg3("--contact-sheet-rank-file: $contactSheetRankFile") if (defined $contactSheetRankFile); ldbg3("--counter-start: $countStart", " --counter-step: $countStep", " --counter-fixed-field: ", boolConv($countFF)); ldbg3("--dry-run: ", boolConv($dryRun)) if (defined $dryRun); ldbg3("--exclude:\n", join("\n", @excludeList)) if (scalar(@excludeList) > 0); ldbg3("--extension: '$extToProcess'"); ldbg3("--keywordize: ", boolConv($keywordize)) if (defined $keywordize); ldbg3("--keywords-replace: ", boolConv($keywordsReplace)) if (defined $keywordsReplace); ldbg3("--keywords-file: $keywordsFile") if (defined $keywordsFile); ldbg3("--mtime: ", boolConv($mtime)) if (defined $mtime); ldbg3("--name-template: $nameTemplate") if (defined $nameTemplate); ldbg3("--no-rename: ", boolConv($noRename), " --no-rotate: ", boolConv($noRotation), " --no-tags: ", boolConv($noTags), " --no-renrot: ", boolConv($noRenRoTagMtm)); ldbg3("--only-orientation: ", boolConv($orientTag)); ldbg3("--rotate-angle: $rotateAngle") if (defined $rotateAngle); ldbg3("--rotate-thumb: $rotateThumbnail") if (defined $rotateThumbnail); ldbg3("--sub-fileset: $subFileSet") if ($subFileSet ne ""); ldbg3("--tag:\n", join("\n", @tmpTags)) if (scalar(@tmpTags) > 0); ldbg3("--trim: ", boolConv($trim)) if (defined $trim); ldbg3("--use-color: ", boolConv($useColor)) if (defined $useColor); ldbg3("--use-ipc: ", boolConv($useIPC)) if (defined $useIPC); ldbg3("--work-directory: $workDir"); ldbg3("ARGV:\n", join("\n", @ARGV)) if ($fileCount > 0); if ($showHelp != 0) { usage(); exit 0; } if ($showVersion != 0) { infomsg ("RenRot version $VERSION (r$REVISION)\n"); exit 0; } if ($extToProcess eq "" and ($fileCount == 0) and $subFileSet eq "") { fatalmsg ("Extension of files is required!\n"); exit 1; } if ($extToProcess ne "" and ($fileCount != 0)) { warnmsg ("Extension of files will be ignored!\n"); } if ($getOptions == 0) { usage(); exit 1; } if ($noRenRoTagMtm != 0) { $noRename = $noRotation = $noTags = 1; $mtime = 0; } # is there ImageMagick? if (defined isTherePackage("Image::Magick")) { $isThereIM = 1; dbgmsg (1, "We have Image::Magick package and could proceed with --contact-sheet related functionality.\n"); } elsif ($cfgOpts{'contact sheet'} == 1 or defined $contactSheet) { errmsg ("To use --contact-sheet related functionality you need Image::Magick package!\n", "Contact Sheet generation disabled.\n"); } elsif ($gen_thm != 0) { errmsg ("To use --generate-thumb functionality you need Image::Magick package!\n", "ThumbnailImage generation is disabled.\n"); } # preparing Software tag according the usage or not of ImageMagick if ($isThereIM == 1) { my ($imName, $imVersion, $dummy) = split(/ /, Image::Magick->new()->Get('version')); $tags{'Software'}{'value'} = sprintf("RenRot v%s (r%s), ExifTool v%s, %s v%s", $VERSION, $REVISION, $Image::ExifTool::VERSION, $imName, $imVersion); } else { $tags{'Software'}{'value'} = sprintf("ExifTool v%s, RenRot v%s (r%s)", $Image::ExifTool::VERSION, $VERSION, $REVISION); } $tags{'Software'}{'group'} = 'EXIF'; # Change user's parameter '*.ext' or 'ext' to '.ext' $extToProcess =~ s/^\*?\.?/\./ if ($fileCount == 0); dbgmsg (1, "Process with '$extToProcess' extension.\n"); # Convert multiple tag parameters to tags hash foreach my $tagStr (@tmpTags) { my %tag = strToHash($tagStr); map { $tagsFromCli{$_} = $tag{$_} } keys %tag; } } ######################################################################################## # Usage : trimValue($value) # Purpose : removes heading and trailing spaces # Returns : trimmed $value # Parameters : $value string # Throws : no exceptions # Comments : none # See Also : N/A sub trimValue { my $value = shift; $value =~ s/\s*([^\s]+.*[^\s]+)\s*/$1/; return $value; } ######################################################################################## # Usage : parsePair() gets (key, value) pair from the string like # : [multiword] key = "value" # Purpose : parses pairs of data # Returns : $key, $value string # Parameters : string like [multiword] key = "value" # Throws : no exceptions # Comments : none # See Also : N/A sub parsePair { my $str = shift; my ($key, $value) = (undef, shift); if ($str =~ m/^([^=]+)=(.+)/) { ($key, $value) = (trimValue($1), trimValue($2)); $value =~ s/^[\'\"](.+)[\'\"]/$1/; # trim quotes dbgmsg (4, "Parsed: '$key' <- '$value'\n"); } elsif ($str =~ m/^([^=]+)=$/) { $key = trimValue($1); dbgmsg (4, "Parsed empty '$key', applying default value: ", defined $value ? "'$value'" : "undef", "\n"); } return ($key, $value); } ######################################################################################## # # strToHash() parses given string to a hash # sub strToHash { my $str = shift; my $default = shift; my %hash = (); $str =~ s/:/=/; # change first entrance of ':' to '=' my ($key, $value) = parsePair($str, $default); if (defined $key) { $key =~ s/\s*[\(\[]([^\(\)\[\]]*)[\)\]]$//; my $group = (defined $1 and $1 ne "") ? $1 : undef; $hash{$key} = {value => $value, group => $group}; # Print debug message $value = "" if (not defined $value); $group = "" if (not defined $group); dbgmsg (4, "Parsed: $key [$group] = '$value'\n"); } else { warnmsg ("Invalid line format: $str\n"); } return %hash; } ######################################################################################## # # getConfig() parses configuration file # sub getConfig { my $fc = shift; my $file = shift; my %hConfig = (); if (open (CFGFILE, "<$file")) { my @cfgfile = ; unless (close (CFGFILE)) { errmsg ("$file wasn't closed!\n"); } $incFiles{$file} = $fc; my $i = 0; while ($i < scalar(@cfgfile)) { my $line = $cfgfile[$i++]; # skip empty and comment lines next if (($line =~ m/^\s*$/) or ($line =~ m/^\s*#/)); $line =~ s/#(.*)$//;# remove trailing comments my ($key, $value) = parsePair($line); if (defined $value) { $key = lc($key); if ($key eq "include" and not $incFiles{$value}) { dbgmsg (2, "Parsing included file: '$value'\n"); %hConfig = parseConfigFile($fc, $value, %hConfig); } $key .= sprintf("#%d#%d", $fc, $i) if (grep (/^$key$/, @multOpts)); $hConfig{$key} = boolConverter($value); dbgmsg (3, "Parsed line($i): '$key' <- '$hConfig{$key}'\n"); } else { warnmsg ("Unparsed line $i in configuration file.\n"); } } } else { errmsg ("Can't open configuration file: $file\n"); } return %hConfig; } ######################################################################################## # # parseConfigFile() parses one file to a hash and merges it with already passed # sub parseConfigFile { my $fc = shift; my $file = shift; my %hConfig = @_; if (-f $file) { my %tmpConfig = getConfig($fc + 1, $file); map { $hConfig{$_} = $tmpConfig{$_} } keys %tmpConfig; } return %hConfig; } ######################################################################################## # # parseConfig() parses user's or standart configuration files to hash # sub parseConfig { my $file = shift; my $home = $ENV{"HOME"}; my @homeRC = (); $home = $ENV{"USERPROFILE"} if (not defined $home); if (defined $home and $home ne "") { push (@homeRC, File::Spec->catfile($home, ".renrotrc")); push (@homeRC, File::Spec->catfile($home, ".renrot", ".renrotrc")); push (@homeRC, File::Spec->catfile($home, ".renrot", "renrot.conf")); } else { warnmsg ("User's home environment variable isn't defined or empty!\n"); } my @rcFiles = ( "/etc/renrot.rc", "/etc/renrot/renrot.rc", "/etc/renrot/renrot.conf", "/usr/local/etc/renrot.rc", "/usr/local/etc/renrot/renrot.rc", "/usr/local/etc/renrot/renrot.conf", @homeRC, ); @rcFiles = ($file) if (defined $file); map { %cfgOpts = parseConfigFile(0, $_, %cfgOpts) } @rcFiles; } ######################################################################################## # # switchColor() switches to user defined color scheme # sub switchColor { # Parse configuration file color set foreach my $cKey (keys %cfgOpts) { next if ($cKey !~ m/^color#\d+#\d+$/); # skip not a color my %color = strToHash($cfgOpts{$cKey}, 'reset'); map { $colors{$_} = $color{$_} } keys %color; } dbgmsg (1, "Switch to user defined color scheme.\n"); } ######################################################################################## # Usage : keywordizer($keywords_file) # Purpose : validates keywords # Returns : [array of strings] @results with CR and LF symbols removed # Parameters : [string] $keywords_file # Throws : no exceptions # Comments : none # See Also : N/A sub keywordizer { my $file = shift; # keywords file return if (not (-R $file and -f $file and -T $file)); dbgmsg (2, "Reading keywords from file: $file\n"); my @result = (); my @keywordArr = getFileDataLines($file); for (my $i = 0; $i < scalar(@keywordArr); $i++) { $keywordArr[$i] =~ s/\r?\n$//; # remove CR and LF symbols push (@result, trimValue($keywordArr[$i])) if ($keywordArr[$i] !~ m/^\s*$/); } return @result; } ######################################################################################## # Usage : renRotProcess($exif_tool_obj, $counter_size) # Purpose : renames and rotates given file set # Returns : nothing # Parameters : $exif_tool_obj [ref] # : $counter_size [num] file name counter digit capacity (number of digits in # : counter. for tens it is 2, for thousands - 4, e.t.c.) # Throws : no exceptions # Comments : none # See Also : N/A sub renRotProcess { my $exifToolObj = shift; my $counterSize = shift; my $fileCounter = $countStart;# file counter my $newFileName; # the name file to be renamed to my $info; # ImageInfo object my @keywordArr = (); # array for keywords if ($cfgOpts{'keywordize'} != 0) { @keywordArr = keywordizer ($cfgOpts{'keywords file'}); errmsg ("Keywords file doesn't exist!\n") if (not -e $cfgOpts{'keywords file'}); } if (scalar(@keywordArr) > 0) { dbgmsg (2, "Keywords count: ", scalar(@keywordArr), "\n"); if ($cfgOpts{'keywords replace'} != 0) { $exifToolObj->SetNewValue(Keywords => \@keywordArr); } else { $exifToolObj->SetNewValue(Keywords => \@keywordArr, AddValue => 1); } } # Convert trim boolean value to string my $trimStr = (not defined $cfgOpts{'trim'} or $cfgOpts{'trim'}) ? '-trim' : ''; dbgmsg (1, "Trim string: '$trimStr'\n"); dbgmsg (1, "Initializing tags...\n"); foreach my $key (sort (keys %tags)) { $exifToolObj->SetNewValue($key, $tags{$key}{value}, Group => $tags{$key}{group}); } procmsg ("RENAMING / ROTATING\n"); procmsg ("===================\n"); my $file_num = scalar(@files); my $file_rem = 0; foreach my $file (@files) { $file_rem++; procmsg ("Processing file: ($file_rem of $file_num) $file...\n"); # Setup defaults $info = $exifToolObj->ImageInfo($file); # analyzing whether to rotate my $angleSuffix = rotateFile($exifToolObj, $info, $file, $trimStr); # generating absent ThumbnailImage tag from the original image if (($isThereIM == 1) and ($gen_thm != 0) and not defined ${$$info{ThumbnailImage}}) { thm_gen_orig($file, 1); } # analyzing whether and how to rename file $newFileName = renameFile($exifToolObj, $info, $file, $fileCounter, $counterSize, $angleSuffix); # to save RenRotFileNameOriginal tag we have to rewrite it each time we anyhow prosess file saveOurHdrs($exifToolObj, $info, $file); # Writing tags. tagWriter($exifToolObj, $newFileName) if ($noTags == 0); # seting mtime for the file if been asked for mtimeSet($exifToolObj, $info, $newFileName); procmsg ("\n"); $fileCounter += $countStep; } } ######################################################################################## # Usage : saveOurHdrs($exif_tool_obj, $info_obj, $file) # Purpose : saves native RenRot defined tags to file EXIF # Returns : nothing # Parameters : $exif_tool_obj [ref] # : $info_obj [ref] # : $file [str] # Throws : no exceptions # Comments : none # See Also : N/A sub saveOurHdrs { my $exifToolObj = shift; my $infoObj = shift; my $file = shift; my $fileNameOriginal = $exifToolObj->GetValue("RenRotFileNameOriginal"); if (not defined $fileNameOriginal) { $tags{'RenRotFileNameOriginal'} = {value => $file, group => 'RenRot'}; dbgmsg (2, "Set RenRotFileNameOriginal to $file.\n"); } else { $tags{'RenRotFileNameOriginal'} = { value => $infoObj->{"RenRotFileNameOriginal"}, group => 'RenRot' }; dbgmsg (2, "RenRotFileNameOriginal: $fileNameOriginal.\n"); } $exifToolObj->SetNewValue("RenRotFileNameOriginal", $tags{'RenRotFileNameOriginal'}{value}, Group => $tags{'RenRotFileNameOriginal'}{group}); } ######################################################################################## # # rotateFile() rotates file and its thumbnail if needed, changes Orientation tag # sub rotateFile { my $exifToolObj = shift; my $infoObj = shift; my $file = shift; my $trimStr = shift; my $orientation = $exifToolObj->GetValue("Orientation", 'ValueConv'); my $angleSuffix = "0cw"; if ($noRotation != 0) { dbgmsg (2, "No rotation asked, file orientation is left untouched.\n"); } elsif (defined $rotateAngle) { dbgmsg (2, "We'll deal with: $file and $rotangles{$rotateAngle}.\n"); if ($orientTag != 0) { rotateOrient($exifToolObj, $file, $orientation); } else { rotateImg($file, $rotangles{$rotateAngle}, $trimStr); rotateThumbnail($infoObj, $file, $rotangles{$rotateAngle}, $trimStr); } $angleSuffix = $rotateAngle . "cw"; } elsif (defined $rotateThumbnail) { rotateThumbnail($infoObj, $file, $rotangles{$rotateThumbnail}, $trimStr); } else { if (defined $orientation) { if ($orientation > 1) { rotateImg($file, $rotparms[$orientation - 1], $trimStr); rotateThumbnail($infoObj, $file, $rotparms[$orientation - 1], $trimStr); $angleSuffix = $angles[$orientation - 1]; } elsif ($orientation == 1) { dbgmsg (2, "No need to rotate, orientation is: Horizontal (normal).\n"); } else { errmsg ("Something wrong, orientation low than 1: $orientation.\n"); } } else { warnmsg ("Orientation tag is absent!\n"); } } return $angleSuffix; } ######################################################################################## # # renameFile() renames file according to user request and EXIF data # sub renameFile { my $exifToolObj = shift; my $infoObj = shift; my $file = shift; my $fileCounter = shift; my $counterSize = shift; my $angleSuffix = shift; my $newFileName; my $unixTime = getUnixTime(getTimestamp($exifToolObj, $infoObj)); if ($noRename != 0) { dbgmsg (2, "No renaming asked, filename is left untouched.\n"); $newFileName = $file; $filenameshash{$newFileName} = $unixTime; } else { my $ext = ($file =~ m/(\.[^\.]+)$/) ? $1 : ""; my $extLen = length($ext); $newFileName = template2name ( $exifToolObj, $infoObj, $cfgOpts{'name template'}, $fileCounter, $file, $counterSize, $angleSuffix ); if ($filenameshash{$newFileName . $ext}) { $newFileName .= "." . sprintf($counterSize, $fileCounter) . $ext; } else { $newFileName .= $ext; } $filenameshash{$newFileName} = $unixTime; if ($file ne $newFileName) { if (-f $newFileName) { fatalmsg ("File $newFileName already exists!\n"), die_renrot(); } if ($dryRun == 0) { rename ($file, $newFileName) || ( fatalmsg ("Unable to rename $file -> $newFileName.\n"), die_renrot() ); } procmsg ("Renamed: $file -> $newFileName\n"); } else { warnmsg ("No renaming needed for $newFileName, it looks as needed!\n"); } } return $newFileName; } ######################################################################################## # # getFileData() gets data from a given file in one-line string # sub getFileData { my $file = shift; my @result = getFileDataLines($file); return join ("", @result) if (scalar(@result) > 0); return undef; } ######################################################################################## # # getFileDataLines() gets data from a given file in array of lines # sub getFileDataLines { my $file = shift; if (not defined $file or $file eq "") { warnmsg ("Can't read file with empty name!\n"); return; } if (open(XXXFILE, "<$file")) { binmode XXXFILE; my @xxxData = ; unless (close(XXXFILE)) { errmsg ("$file wasn't closed!\n"); } return @xxxData; } warnmsg ("Can't read file: $file!\n"); return; } ######################################################################################## # # getFileDatLns() gets data from a given file in array of lines. it returns hash # of format: $hash{'field1'}[0] => 1 # ... # $hash{'field1'}[N] => fieldN # where N is the number of fields, starting from 1 # sub getFileDatLns { my $file = shift; # name of the file to be processed if (not defined $file or $file eq "") { warnmsg ("Can't read file with empty name!\n"); return; } if (open(XXXFILE, "<$file")) { binmode XXXFILE; my %xxxData; # splited line hash my @chunks = (); # arr, chunks to be placed to my ($i, $j); while (){ chomp; @chunks = split(/\s+/); $xxxData{$chunks[0]}[0] = 1; for ($i = 1; $i < scalar(@chunks); $i++) { $xxxData{$chunks[0]}[$i] = $chunks[$i]; dbgmsg (4, "xxxData{$chunks[0]}[$i] = $chunks[$i]\n"); } undef @chunks; } unless (close(XXXFILE)) { errmsg ("$file wasn't closed!\n"); } return \%xxxData; } warnmsg ("Can't read file: $file!\n"); return; } ######################################################################################## # # mtimeSet() sets mtime for the given file # sub mtimeSet { my $exifToolObj = shift; my $infoObj = shift; my $file = shift; if ($cfgOpts{'mtime'} != 0) { my $mTime = getUnixTime(getTimestamp($exifToolObj, $infoObj)); if ($dryRun == 0) { utime $mTime, $mTime, $file; } else { procmsg ("Setting mtime.\n"); } dbgmsg (2, "Changing mtime for $file OK.\n"); } } ######################################################################################## # # tagWriter() writes couple of tags defined via configuration file and command line # sub tagWriter { my $exifToolObj = shift; my $file = shift; # writing the changes to the EXIFs if ($dryRun == 0) { exifWriter($exifToolObj, $file); } else { procmsg ("Writing user defined EXIF tags to $file.\n"); } } ######################################################################################## # # exifWriter() applies EXIF info, set by SetNewValue, to the image taken from # the file, and writes the result to the same file. # sub exifWriter { my $exifToolObject = shift; my $fileRes = shift; # the file the *image* taken from my $result = $exifToolObject->WriteInfo($fileRes); if ($result == 1) { dbgmsg (2, "Writing to $fileRes seems to be OK.\n"); } elsif ($result == 2) { warnmsg ("No EXIF difference. No EXIF was written.\n"); } else { my $errorMessage = $exifToolObject->GetValue('Error'); my $warningMessage = $exifToolObject->GetValue('Warning'); if (defined $errorMessage) { errmsg ("ExifTool: $errorMessage\n"); } if (defined $warningMessage) { warnmsg ("ExifTool: $warningMessage\n"); } } return $result; } ######################################################################################## # # aggregationProcess() aggregates files to separate directories by request # sub aggregationProcess { return if ($cfgOpts{'aggregation mode'} eq "none"); my $exifToolObj = shift; my $counterSize = shift; my $file; my $info; my $BaseDir = $cfgOpts{'aggregation directory'}; my $NewDir; my $file_num = scalar(keys(%filenameshash)); my $file_rem = 0; procmsg ("AGGREGATION\n"); procmsg ("===========\n"); makeDir($BaseDir); if ($cfgOpts{'aggregation mode'} eq "template") { dbgmsg (1, "Template: $cfgOpts{'aggregation template'}\n"); my $fileCounter = $countStart; foreach $file (sort (keys %filenameshash)) { $file_rem++; $info = $exifToolObj->ImageInfo($file); $NewDir = template2name ( $exifToolObj, $info, $cfgOpts{'aggregation template'}, $fileCounter, $file, $counterSize, "0cw" ); $NewDir = File::Spec->catdir($BaseDir, $NewDir); aggregateFile($file, $NewDir) if ($dryRun == 0); procmsg ("Aggregate: ($file_rem of $file_num) $file -> $NewDir\n", "\n"); $fileCounter += $countStep; } } elsif ($cfgOpts{'aggregation mode'} eq "delta") { my $DirCounter = 1; my $timestampPrev; my $filePrev; my $filetmp; foreach $file (sort (keys %filenameshash)) { $filetmp = $file; $file_rem++; if ($DirCounter == 1) { $timestampPrev = $filenameshash{$filetmp}; $filePrev = $filetmp; $NewDir = $BaseDir . "." . sprintf($counterSize, $DirCounter); $DirCounter++; aggregateFile($file, $NewDir) if ($dryRun == 0); } else { # Check for new direcroty creation if (($filenameshash{$filetmp} - $timestampPrev) > $cfgOpts{'aggregation delta'}) { $NewDir = $BaseDir . "." . sprintf($counterSize, $DirCounter); $DirCounter++; } aggregateFile($file, $NewDir) if ($dryRun == 0); $timestampPrev = $filenameshash{$filetmp}; } procmsg ("Aggregate: ($file_rem of $file_num) $file -> $NewDir\n", "\n"); } } else { errmsg ("Aggregation mode $cfgOpts{'aggregation mode'} isn't implemented!\n"); } } ######################################################################################## # Usage : contactSheetGenerator(); # Purpose : builds contact sheet/s # Returns : none # Parameters : $exifTool ref - # Throws : no exceptions # Comments : requires --ext; --counter-start is valid # See Also : template2name() sub contactSheetGenerator { return if (not $cfgOpts{'contact sheet'}); use File::Copy; my $exifToolObj = shift; my $workdir = $cfgOpts{'contact sheet dir'}; my $file; my $info; my $infothm; my $ThumbnailOriginal; my $width; my $height; my $size = 0; my @thumbnailes = (); my @thumbnailes_sorted = (); my $orientation; my $filefull; my $ranks; # reference to the hash of files ranks # ranks file processing if ($cfgOpts{'contact sheet rank'} == 1 and -f $cfgOpts{'contact sheet rank file'}) { $ranks = getFileDatLns($cfgOpts{'contact sheet rank file'}); if ($ranks != 0) { dbgmsg (3, "Ranks successfully processed.\n"); } else { errmsg ("Ranks processing failed.\n"); } } makeDir($workdir); procmsg ("CONTACT SHEET GENERATION\n"); procmsg ("========================\n"); # no sort since it'll be sorted below foreach $file (keys %filenameshash) { $info = $exifToolObj->ImageInfo($file); $orientation = $exifToolObj->GetValue("Orientation", 'ValueConv'); $filefull = $file; if ($contactSheetThm != 0 and defined $orientation) { if ($orientation > 1) { $filefull = rot_thm_cs ($file, $rotorient{$orientation}, $workdir); } elsif ($orientation == 1) { # We need this since rotated imgage will be at $workdir, but others are # in current $ThumbnailOriginal = File::Spec->catfile($workdir, $file); copy ($file, $ThumbnailOriginal) || ( fatalmsg ("copy failed: $!"), die_renrot() ); $filefull = $ThumbnailOriginal; } } elsif ($contactSheetThm == 0) { if (defined ${$$info{ThumbnailImage}}) { $ThumbnailOriginal = File::Spec->catfile($workdir, $file); open (OLDTHUMBNAIL, ">$ThumbnailOriginal") || ( fatalmsg ("$ThumbnailOriginal wasn't opened!\n"), die_renrot() ); binmode OLDTHUMBNAIL; print OLDTHUMBNAIL ${$$info{ThumbnailImage}}; unless (close (OLDTHUMBNAIL)) { warnmsg ("$ThumbnailOriginal wasn't closed!\n"); } if (not defined $orientation) { $orientation = $exifToolObj->GetValue("Rotation", 'ValueConv'); } if (defined $orientation and $orientation > 1) { $filefull = rot_thm_cs ($ThumbnailOriginal, $orientation, File::Spec->curdir()); } else { $filefull = $ThumbnailOriginal; } } else { my $ffwf = File::Spec->catfile($workdir, $file); if ($gen_thm == 0) { warnmsg ("$filefull has no ThumbnailImage tag. Stub thumbnail image will be used.\n"); my $thmbstubjpg = File::Spec->catfile($workdir, "thmbstub.jpg"); thm_gen_stub($thmbstubjpg) if (not -f $thmbstubjpg); copy ($thmbstubjpg, $ffwf); } else { warnmsg ("$filefull has no ThumbnailImage tag. Thumbnail image will be generated.\n"); move (thm_gen_orig($file, 0), $ffwf); } $filefull = $ffwf; } } $infothm = $exifToolObj->ImageInfo($filefull); $width = $exifToolObj->GetValue("ImageWidth"); $height = $exifToolObj->GetValue("ImageHeight"); if ($width > $size) { $size = $width; } if ($height > $size) { $size = $height; } push (@thumbnailes, $filefull); } @thumbnailes_sorted = sort {$a cmp $b} @thumbnailes; ldbg3("contact sheet background = \"$cfgOpts{'contact sheet background'}\""); ldbg3("contact sheet bordercolor = \"$cfgOpts{'contact sheet bordercolor'}\""); ldbg3("contact sheet mattecolor = \"$cfgOpts{'contact sheet mattecolor'}\""); ldbg3("contact sheet font = \"$cfgOpts{'contact sheet font'}\""); ldbg3("contact sheet label = \"$cfgOpts{'contact sheet label'}\""); ldbg3("contact sheet frame = \"$cfgOpts{'contact sheet frame'}\""); ldbg3("contact sheet pointsize = \"$cfgOpts{'contact sheet pointsize'}\""); ldbg3("contact sheet shadow = \"$cfgOpts{'contact sheet shadow'}\""); ldbg3("contact sheet title = \"$cfgOpts{'contact sheet title'}\""); ldbg3("contact sheet tile = \"$cfgOpts{'contact sheet tile'}\""); # here it's iteration by tile my ($tileX, $tileY) = split ("x", $cfgOpts{'contact sheet tile'}); my $tileMul = $tileX * $tileY; my $csIterationNumber = scalar @thumbnailes_sorted; my $csFullIterations = int($csIterationNumber/$tileMul); my $csRest = $csIterationNumber % $tileMul; my $fileCounter = $countStart; my $csIteration = 0; my $csIterator = 0; my $csIter = 0; my $readres; my $image; my $writeres; my $montage; my $montagename; my $infoMontage; my @left_up_row = ("RenRot v$VERSION (r$REVISION)", $homeURL); my $substrFile; my $readIndex; my $counter_size; if ($csFullIterations != 0) { $counter_size = "%." . length($csFullIterations * $countStep + $countStart) . "d"; dbgmsg (1, "Counter size: $size (CS files num: $csFullIterations)\n"); } else { $counter_size = "%d"; } if ($csFullIterations > 0) { # we need this for the case when $csRest == 0 and $csIterationNumber > $tileMul if (not $csRest) { --$csFullIterations; } for (; $csIterator < $csFullIterations; $csIterator++, $fileCounter += $countStep) { $image = Image::Magick->new; $montagename = template2name ( $exifToolObj, $info, $cfgOpts{'contact sheet file'}, $fileCounter, "stub", $counter_size, "none" ); for ($readIndex = 0, $csIter = $csIterator * $tileMul; $csIter < ($csIterator * $tileMul + $tileMul); $csIter++, $readIndex++) { $readres = $image->Read($thumbnailes_sorted[$csIter]); if (not $readres) { dbgmsg (4, "$thumbnailes_sorted[$csIter] was successfully read.\n"); } else { errmsg ("Image::Magick error: $readres\n"); } # ranking $substrFile = substr($thumbnailes_sorted[$csIter], length($cfgOpts{'contact sheet dir'}) + 1); if (defined $ranks->{$substrFile}->[1]) { dbgmsg (4, "$substrFile mattecolor is \"$ranks->{$substrFile}->[1]\"\n"); $image->[$readIndex]->Set(mattecolor => $ranks->{$substrFile}->[1]); } else { dbgmsg (4, "$substrFile mattecolor is undefined, using \"$cfgOpts{'contact sheet mattecolor'}\" from config\n"); $image->[$readIndex]->Set(mattecolor => normalize_color($cfgOpts{'contact sheet mattecolor'})); } } dbgmsg (1, "$csIterator montage is started, wait a bit please...\n"); $montage = $image->Montage(background => normalize_color($cfgOpts{'contact sheet background'}), bordercolor => normalize_color($cfgOpts{'contact sheet bordercolor'}), font => $cfgOpts{'contact sheet font'}, fill => normalize_color($cfgOpts{'contact sheet fill'}), label => $cfgOpts{'contact sheet label'}, frame => $cfgOpts{'contact sheet frame'}, geometry => $size . "x" . $size . "+4+4", pointsize => $cfgOpts{'contact sheet pointsize'}, shadow => $cfgOpts{'contact sheet shadow'}, title => $cfgOpts{'contact sheet title'}, tile => $cfgOpts{'contact sheet tile'}, stroke => 'none', ); if (not ref($montage)) { errmsg ("Image::Magick error: $montage\n"); } else { dbgmsg (1, "$csIterator montage've finished successfully.\n"); } $montage->Set ( filename => 'jpg:' . $montagename, quality => 95, interlace => 'Partition', gravity => 'Center', stroke => 'none', ); $montage->Annotate ( font => $cfgOpts{'contact sheet font'}, pointsize => 9, x => 5, y => 13, fill => 'lightgray', text => $left_up_row[0], ); $montage->Annotate ( font => $cfgOpts{'contact sheet font'}, pointsize => 9, x => 5, y => 23, fill => 'lightgray', text => $left_up_row[1], ); $writeres = $montage->Write(); if (not $writeres) { dbgmsg (1, "Successfully written $montagename file.\n"); } else { errmsg ("Image::Magick error: $writeres\n"); } $infoMontage = $exifToolObj->ImageInfo($montagename); # to save RenRotFileNameOriginal tag we have to rewrite it each time we anyhow prosess file saveOurHdrs($exifToolObj, $infoMontage, $montagename); # Writing tags. tagWriter($exifToolObj, $montagename); # Writing ThumbnailImage tag with generated thumbnail thm_gen_orig($montagename, 1); undef $image; } } $image = Image::Magick->new; $montagename = template2name ( $exifToolObj, $info, $cfgOpts{'contact sheet file'}, $fileCounter, "stub", $counter_size, "none" ); for ($readIndex = 0, $csIteration = $csIterator * $tileMul; $csIteration < $csIterationNumber; $csIteration++, $readIndex++) { $readres = $image->Read($thumbnailes_sorted[$csIteration]); if (not $readres) { dbgmsg (4, "$thumbnailes_sorted[$csIteration] was successfully red.\n"); } else { errmsg ("Image::Magick error: $readres\n"); } # ranking $substrFile = substr($thumbnailes_sorted[$csIteration], length($cfgOpts{'contact sheet dir'}) + 1); if (defined $ranks->{$substrFile}->[1] and length($ranks->{$substrFile}->[1]) > 1) { dbgmsg (4, "[last] $substrFile mattecolor is \"$ranks->{$substrFile}->[1]\"\n"); $image->[$readIndex]->Set(mattecolor => $ranks->{$substrFile}->[1]); } else { dbgmsg (4, "[last] $substrFile mattecolor is undefined, using \"$cfgOpts{'contact sheet mattecolor'}\" from config.\n"); $image->[$readIndex]->Set(mattecolor => normalize_color($cfgOpts{'contact sheet mattecolor'})); } } dbgmsg (1, "Final, $csIterator montage is started, wait a bit please...\n"); # the final invocation of ->Montage() method for the the rest of files didn't fit # previous loop ->Montage() calls when $csIterationNumber < $tileX * $tileY $montage = $image->Montage ( background => normalize_color($cfgOpts{'contact sheet background'}), bordercolor => normalize_color($cfgOpts{'contact sheet bordercolor'}), font => $cfgOpts{'contact sheet font'}, fill => normalize_color($cfgOpts{'contact sheet fill'}), label => $cfgOpts{'contact sheet label'}, frame => $cfgOpts{'contact sheet frame'}, geometry => $size . "x" . $size . "+4+4", pointsize => $cfgOpts{'contact sheet pointsize'}, shadow => $cfgOpts{'contact sheet shadow'}, title => $cfgOpts{'contact sheet title'}, tile => $cfgOpts{'contact sheet tile'}, stroke => 'none', ); if (not ref($montage)) { errmsg ("Image::Magick error: $montage\n"); } else { dbgmsg (1, "Montage've finished successfully.\n"); } $montage->Set ( filename => 'jpg:' . $montagename, quality => 95, interlace => 'Partition', gravity => 'Center', stroke => 'none', ); $montage->Annotate ( font => $cfgOpts{'contact sheet font'}, pointsize => 9, x => 5, y => 13, fill => 'lightgray', text => $left_up_row[0], ); $montage->Annotate ( font => $cfgOpts{'contact sheet font'}, pointsize => 9, x => 5, y => 23, fill => 'lightgray', text => $left_up_row[1], ); $writeres = $montage->Write(); if (not $writeres) { dbgmsg (1, "Successfully written $montagename file.\n"); } else { errmsg ("Image::Magick error: $writeres\n"); } undef $image; $infoMontage = $exifToolObj->ImageInfo($montagename); # to save RenRotFileNameOriginal tag we have to rewrite it each time we anyhow prosess file saveOurHdrs($exifToolObj, $infoMontage, $montagename); # Writing tags. tagWriter($exifToolObj, $montagename); # Writing ThumbnailImage tag with generated thumbnail thm_gen_orig($montagename, 1); chdir $workdir; unlink <*>; chdir ".."; rmdir $workdir; } ######################################################################################## # Usage : thm_gen_stub($thm_name); # Purpose : thumbnail stub generator # Returns : none # Parameters : $thm_name str - thumbnail image pathname # Throws : no exceptions # Comments : none # See Also : contactSheetGenerator(); sub thm_gen_stub { my $thm_name = shift; my $size = $cfgOpts{'generate thumbnail size'}; my $thmb = Image::Magick->new; $thmb->Set(size => $size, filename => $thm_name, quality => 95, interlace => 'Partition'); $thmb->ReadImage("gradient:" . normalize_color($cfgOpts{'contact sheet thm grad fr'}) . "-" . normalize_color($cfgOpts{'contact sheet thm grad to'})); $thmb->Annotate ( pointsize => 25, fill => normalize_color($cfgOpts{'contact sheet thm fill'}), font => $cfgOpts{'contact sheet thm font'}, text => $cfgOpts{'contact sheet thm text'}, gravity => 'Center', ); my $thmbnum = $thmb->Write(); if ($thmbnum) { errmsg ("$thmbnum\n"); } undef $thmb; procmsg ("Stub thumbnail image has been created.\n"); } ######################################################################################## # Usage : thm_gen_orig($file, $unlink); # Purpose : generate thumbnail image from the original file and write it # : to the ThumbnailImage tag # Returns : thumbnail file name if unlink not asked # Parameters : $file str - original image name # : $unlink bin - 0 not to kill generated thumbnail # : 1 to kill generated thumbnail # Throws : no exceptions # Comments : none # See Also : n/a sub thm_gen_orig { my $file = shift; my $unlink = shift; my $thm_name = "thm_" . $file; my $size = $cfgOpts{'generate thumbnail size'}; my $thmb = Image::Magick->new; $thmb->Set(size => $size, filename => $thm_name, quality => 95, interlace => 'Partition'); $thmb->ReadImage($file); $thmb->Thumbnail(geometry => $size); my $thmbnum = $thmb->Write(); if ($thmbnum) { errmsg ("$thmbnum\n"); } undef $thmb; if ($unlink) { dbgmsg (3, "Attempt to write ThumbnailImage tag to $file\n"); thumbWriter($file, getFileData($thm_name)); unlink $thm_name; } else { dbgmsg (3, "ThumbnailImage was generated for $file\n"); return $thm_name; } } ######################################################################################## # Usage : rot_thm_cs($base_orig, $angle, $workdir); # Purpose : rotates thumbnails for contact sheet and put it to the workdir # Returns : none # Parameters : $base_orig str - pathless filename of the rotated file # : $angle num - rotation angle # : $workdir str - the work directory thumbnails kept in # Throws : no exceptions # Comments : works only with JPEGs # See Also : contactSheetGenerator(); sub rot_thm_cs { my $base_orig = shift; my $angle = shift; my $workdir = shift; my $image_to_rotate = Image::Magick->new; my $result = File::Spec->catfile($workdir, $base_orig); $image_to_rotate->Read("JPEG:" . $base_orig); $image_to_rotate->Rotate(degrees => $angle); $image_to_rotate->Write(filename => "JPEG:" . $result, quality => 95, compression => 'JPEG2000'); undef $image_to_rotate; return $result; } ######################################################################################## # Usage : normalize_color($color); # Purpose : validates given string as color suitable for ImageMagick # Returns : none # Parameters : $color str - color # Throws : no exceptions # Comments : none # See Also : convert -list color sub normalize_color { my $color = shift; if ($color =~ /^#?([[:xdigit:]]{3})$/ or $color =~ /^#?([[:xdigit:]]{6})$/) { return "#" . $1; } return $color; } ######################################################################################## # Usage : makeDir($dir); # Purpose : makes one level directory # Returns : none # Parameters : $dir str - directory to make # Throws : no exceptions # Comments : none # See Also : n/a sub makeDir { my $new_dir = shift; if (not -d $new_dir) { eval { mkpath($new_dir, 0, 0700) }; if ($@) { errmsg ("Couldn't create $new_dir: $@"); } } } ######################################################################################## # Usage : aggregateFile($file, $NewDir); # Purpose : moves or links file to the aggregation directory # Returns : none # Parameters : $file [str] - name of file to be moved # : $new_dir [str] - name of dir the file to be moved to # Throws : no exceptions # Comments : none # See Also : N/A sub aggregateFile { my $file = shift; my $new_dir = shift; my ($dummy_volume, $dummy_dir, $base_name) = File::Spec->splitpath($file); makeDir($new_dir); if ($cfgOpts{'aggregation virtual'} == 0) { my $newname = File::Spec->catfile($new_dir, $base_name); rename ($file, $newname) || ( fatalmsg ("While moving $file -> $newname, perhaps a different file system is using\n"), die_renrot() ); dbgmsg (3, "$file moved to $newname\n"); } else { my $newfile = File::Spec->catfile(File::Spec->abs2rel($new_dir), $base_name); if (not -l $newfile) { # Make relative path to original file from new directory my $oldfile = File::Spec->catfile(File::Spec->abs2rel(File::Spec->curdir(), $new_dir), $file); symlink ($oldfile, $newfile) || ( fatalmsg ("While linking $oldfile -> $newfile\n"), die_renrot() ); dbgmsg (3, "Following link was created $newfile -> $oldfile\n"); } else { warnmsg ("Link $newfile already exists.\n"); } } } ######################################################################################## # Usage : timeNow(); # Purpose : builds timestamp in form YYYYmmddHHMMSS # Returns : string # Parameters : none # Throws : no exceptions # Comments : none # See Also : n/a sub timeNow { my $date = localtime(); my $time_now = sprintf("%.4d%.2d%.2d%.2d%.2d%.2d", $$date[5] + 1900, $$date[4] + 1, $$date[3], $$date[2], $$date[1], $$date[0]); return $time_now; } ######################################################################################## # # timeValidator() returns correctness of timestamp in form YYYYmmddHHMMSS # sub timeValidator { my $timestamp = shift; # check length (14) return 1 if (length($timestamp) != 14); my @tm = ($timestamp =~ m/(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)/); return 1 unless @tm == 6; dbgmsg (4, "@tm\n"); if ( # check year ($tm[0] < 1900) or # check month (($tm[1] > 12) or ($tm[1] < 1)) or # check day (($tm[2] > 31) or ($tm[2] < 1)) or # check hour, minute, second ($tm[3] > 23) or ($tm[4] > 59) or ($tm[5] > 59) ) { return 1; } return 0; } ######################################################################################## # # getTimestamp() returns EXIF timestamp in form YYYYmmddHHMMSS if exists, otherwise # it returns timeNow() # sub getTimestamp { my $exifToolObj = shift; my $infoObj = shift; my $timestamp; if (defined $infoObj->{"DateTimeOriginal"} and not timeValidator($infoObj->{"DateTimeOriginal"})) { $timestamp = $infoObj->{"DateTimeOriginal"}; } elsif (defined $infoObj->{"FileModifyDate"} and not timeValidator($infoObj->{"FileModifyDate"})) { $timestamp = $infoObj->{"FileModifyDate"}; } else { $timestamp = timeNow(); $exifToolObj->SetNewValue('FileModifyDate', $timestamp, Group => 'File'); warnmsg ("EXIF timestamp isn't correct, using current time!\n"); } return $timestamp; } ######################################################################################## # # getUnixTime() converts timestamp to unix time form # sub getUnixTime { my $timestamp = shift; my @tm = ($timestamp =~ m/(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)/); $tm[0] -= 1900; # convert year $tm[1] -= 1; # convert month @tm = reverse @tm; # change to order required by timelocal() return Time::Local::timelocal(@tm); } ######################################################################################## # # rotateOrient() rotates image by changing Orientation tag. No real rotation # will be made. # sub rotateOrient { my $exifToolObj = shift; my $fileOrient = shift; my $orientation = shift; dbgmsg (4, "Original Orientation: $orientation\n"); my $angleTmp = $rotorient{$orientation}; if (not defined $angleTmp) { errmsg ("Operation not permited for mirror type orientation.\n"); return; } $angleTmp += $rotateAngle; $angleTmp -= 360 if ($angleTmp >= 360); $orientation = $rotorientrev{$angleTmp}; dbgmsg (4, "New Orientation: $orientation\n"); $exifToolObj->SetNewValue("Orientation", $orientation, Type => 'ValueConv'); if ($dryRun == 0) { exifWriter($exifToolObj, $fileOrient); } else { procmsg ("Rotating Orientation tag value.\n"); } } ######################################################################################## # # rotateImg() rotates the image file by given angle # sub rotateImg { my $oldfile = shift; # original name to transform with jpegtran my $origfile = $oldfile . "_orig"; # backup original name my $newfile = $oldfile . "_rotated"; # temporay name to store rotated file my @addon = @_; # the switches for jpegtran to transform the image # jpegtran the image my $cmd = "jpegtran -copy none @addon -outfile \"$newfile\" \"$oldfile\""; dbgmsg (3, "$cmd\n"); system $cmd || ( fatalmsg ("System $cmd failed: $?\n"), die_renrot() ); # preparing to write tags to the just rotated file my $exifAfterRot = new Image::ExifTool; $exifAfterRot->Options(Binary => 1); $exifAfterRot->SetNewValuesFromFile($oldfile, '*:*'); $exifAfterRot->SetNewValue("Orientation", 1, Type => 'ValueConv'); if ($backup != 0) { rename ($oldfile, $origfile) || ( fatalmsg ("$oldfile -> $origfile\n"), die_renrot() ); } rename ($newfile, $oldfile) || ( fatalmsg ("$newfile -> $oldfile\n"), die_renrot() ); # writing the changes to the EXIFs exifWriter($exifAfterRot, $oldfile); } ######################################################################################## # # thumbWriter() writes binary data as thumbnail to given file # sub thumbWriter { my $file = shift; my $thethumb = shift; # preparing to write thumbnale to the just rotated file my $exifThumbnailed = new Image::ExifTool; $exifThumbnailed->Options(Binary => 1); $exifThumbnailed->SetNewValue("ThumbnailImage", $thethumb, Type => 'ValueConv'); # writing the changes to the EXIFs exifWriter($exifThumbnailed, $file); } ######################################################################################## # # rotateThumbnail() rotates thumbnail only, where the file was rotated but # thumbnail was left untouched # sub rotateThumbnail { my $infoObj = shift; my $file = shift; # file, which thumbnale to transform with jpegtran my @addon = @_; # the switches for jpegtran to rotate the thumbnail if (not defined ${$$infoObj{ThumbnailImage}}) { warnmsg ("No thumbnail found.\n"); return; } my $origThumb = ${$$infoObj{ThumbnailImage}}; if ($cfgOpts{'use ipc'} == 0) { # extracting the thumbnail image my $ThumbnailOriginal = $file . "_thumborig"; unless (open (OLDTHUMBNAIL, ">$ThumbnailOriginal")) { errmsg ("$ThumbnailOriginal wasn't opened!\n"); } binmode OLDTHUMBNAIL; print OLDTHUMBNAIL $origThumb; unless (close (OLDTHUMBNAIL)) { warnmsg ("$ThumbnailOriginal wasn't closed!\n"); } # rotating the thumbnail my $ThumbnailOriginalRotated = $ThumbnailOriginal . "_rotated"; my $cmd = "jpegtran -copy none @addon -outfile \"$ThumbnailOriginalRotated\" \"$ThumbnailOriginal\""; dbgmsg (3, "$cmd\n"); system $cmd || ( fatalmsg ("System $cmd failed: $?\n"), die_renrot() ); # write the just rotated thumbnail back to file thumbWriter($file, getFileData($ThumbnailOriginalRotated)); unlink ($ThumbnailOriginalRotated) || ( fatalmsg ("While killing $ThumbnailOriginalRotated.\n"), die_renrot() ); unlink ($ThumbnailOriginal) || ( fatalmsg ("While killing $ThumbnailOriginal.\n"), die_renrot() ); } else { my $cmd = "jpegtran -copy none @addon"; dbgmsg (3, "$cmd\n"); # write the just rotated thumbnail back to file thumbWriter($file, piper($origThumb, $cmd)); } } ######################################################################################## # Usage : piper(); # Purpose : opens two pipes for process object via the command passed as argument # Returns : $pipe_obj processed via $pipe_cmd # Parameters : $pipe_obj bin - the object to be processed via pipe # : $pipe_cmd str - the command for the processing # Throws : no exceptions # Comments : none # See Also : n/a sub piper { use FileHandle; use IPC::Open2; my $pipe_obj = shift; # the object to be processed via pipe my $pipe_cmd = shift; # the pipe command local (*READ_FROM_FH, *WRITE_TO_FH); # file handlers unless (open2(\*READ_FROM_FH, \*WRITE_TO_FH, $pipe_cmd)) { errmsg ("Unable to create the pipe.\n"); } binmode WRITE_TO_FH; print WRITE_TO_FH $pipe_obj; unless (close(WRITE_TO_FH)) { warnmsg ("WRITE handle wasn't closed!\n"); }; binmode READ_FROM_FH; my @piped_arr = ; unless (close(READ_FROM_FH)) { warnmsg ("READ handle wasn't closed!\n"); }; return join("", @piped_arr); } ######################################################################################## # # usage() prints the instructions how to use the script # sub usage { infomsg ( "Usage: renrot <--extension EXTENSION> [--quiet] [--no-rotate] [--no-rename] [--name-template TPL] [--comment-file FILE] [--work-directory DIR] [[--] FILE1 FILE2 ...] Options: -c, --config-file configuration file to use -d, --work-directory set working directory --exclude ... files exclude from processing; no wildcards --sub-fileset read names of the files to be processed from FILE -e, --extension extension of files to process: JPG, jpeg, ... Renaming options: -n, --name-template filename template (see manual for details) --no-rename do not rename files (default is to rename) --counter-fixed-field (*) set fixed field width for counter (used in templates) --counter-start start value for the counter of renamed files --counter-step increment value for the counter of renamed files Rotating options: -r, --rotate-angle angle to rotate files and thumbnails by 90, 180, 270 --rotate-thumb rotate only thumbnails by 90, 180, 270 --only-orientation change Orientation tag (no real rotation) --no-rotate do not rotate (default is to rotate) --trim (*) pass -trim to jpegtran --mtime (*) set file mtime according to DateTimeOriginal tag Keywordizing options: --keywordize (*) set Keywords tag --keywords-replace (*) replace Keywords tag rather than add values to it -k, --keywords-file read keywords from FILE Aggregating options: --aggr-mode run aggregation (MODE: none, delta, template) --aggr-delta aggregation time delta --aggr-directory aggregation directory name -a, --aggr-template aggregation template (see manual for details) --aggr-virtual (*) virtual aggregation (symlinks instead of files) Contact Sheet options (CS): --cs (*) create the CS --cs-tile tile in montage --cs-title set title of the montage --cs-file name of the montage files --cs-dir temporary montage DIR --cs-thm montage files are thumbnails --cs-bg background color (IM: -background) --cs-bd border color (IM: -bordercolor) --cs-mt frame color (IM: -mattecolor) --cs-fn text render font (IM: -font) --cs-fl color to fill the text (IM: -fill) --cs-lb image label (IM: -label) --cs-fr thickness of border (IM: -frame) --cs-pntsz font point size (IM: -pointsize) --cs-shadow set shadow (IM: -shadow) --cs-thm-fl generated thumbnail text fill color --cs-thm-fn generated thumbnail font --cs-thm-grfr generated thumbnail background gradient COLOR-from --cs-thm-grto generated thumbnail background gradient COLOR-to --cs-thm-text generated thumbnail text --cs-rank to do CS ranking --cs-rank-file file with CS ranks Tag writing options: --comment-file file with text to put into Commentary tag --user-comment file with text to put into UserComment tag -t, --tag ... existing EXIF tag to set in renamed files --no-tags do not write tags Colorizing options: --use-color (*) colorized output Misc options: -g, --generate-thumb generation, writing or rewriting ThumbnailImage tag --dry-run do nothing, only print would have been done --use-ipc (*) rotate thumbnail via pipe, rather than via file -v increment debugging level by 1 -h, --help display this help and exit --version output version and exit (*) The options marked with this sign do not take arguments and can be negated, i.e. prefixed by 'no'. E.g. '--mtime' sets file mtime value, while '--nomtime' or '--no-mtime' disables setting it. "); } ######################################################################################## # Usage : $name = template2name(...); # Purpose : builds file name according to the template # Returns : name as string # Parameters : $exifToolObj [ref] - # : $infoObj [ref] - # : $template [str] - the template to be used # : $fileNo [num] - counter for %c # : $fileName [str] - file name for %n and %e # : $counterSize [num] - the size of the counter for format (like "01", "0012") # : $angleSuffix [str] - suffix to add to the end of the rotated files # Throws : no exceptions # Comments : none # See Also : n/a sub template2name { my $exifToolObj = shift; my $infoObj = shift; my $template = shift; my $fileNo = shift; my $fileName = shift; my $counterSize = shift; my $angleSuffix = shift; my ($base, $ext); # file name %n and extension %e if ($fileName =~ m/^(.*)\.([^\.]+)$/) { $base = $1; $ext = $2; } else { $base = $fileName; $ext = ''; } if (not defined $template) { fatalmsg ("Template isn't given!\n"), die_renrot(); } my $timestamp = getTimestamp($exifToolObj, $infoObj); my @tm = ($timestamp =~ m/(\d\d(\d\d))(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)/); dbgmsg (4, "tm: @tm\n"); my $ExposureTime = ""; my $FileNumber = 'NA'; my $FNumber = ""; my $ISO = ""; my $WhiteBalance = ""; my $fileNameOriginal = ""; my $fileNameOriginalCounter = ""; # we can not use 0 as default value my $fileNameOriginalExtensionLess = ""; if (defined $infoObj->{"FileNumber"}) { $FileNumber = $infoObj->{"FileNumber"}; } if (defined $infoObj->{"ExposureTime"}) { $ExposureTime = $infoObj->{"ExposureTime"}; $ExposureTime =~ s/\//by/g; } if (defined $infoObj->{"FNumber"}) { $FNumber = $infoObj->{"FNumber"}; } if (defined $infoObj->{"ISO"}) { $ISO = $infoObj->{"ISO"}; } if (defined $infoObj->{"WhiteBalance"}) { $WhiteBalance = $infoObj->{"WhiteBalance"}; $WhiteBalance =~ s/[\s()]//g; } if (defined $infoObj->{"RenRotFileNameOriginal"}) { $fileNameOriginal = $infoObj->{"RenRotFileNameOriginal"}; } else { # Temporary stub to make renrot remember original file name for the formats # ExifTool writing to doesn't support. # Reported by Neil Hooey $fileNameOriginal = $infoObj->{"FileName"}; } # file name starts with letters and ends with digits if ($fileNameOriginal =~ m/^[[:alpha:]\-_]*(\d+)(\.[^\.]+)?$/) { $fileNameOriginalCounter = $1; } if ($fileNameOriginal =~ m/^(.*)\.([^\.]+)$/) { $fileNameOriginalExtensionLess = $1; } my @templatearea = split (//, $template); my %templatehash = ( '%' => "%", '#' => "#", 'a' => $angleSuffix, 'C' => $fileNameOriginalCounter, 'c' => sprintf($counterSize, $fileNo), 'd' => $tm[3], 'E' => $ExposureTime, 'e' => $ext, 'F' => $FNumber, 'H' => $tm[4], 'I' => $ISO, 'i' => $FileNumber, 'M' => $tm[5], 'm' => $tm[2], 'n' => $base, 'O' => $fileNameOriginalExtensionLess, 'o' => $fileNameOriginal, 'S' => $tm[6], 'W' => $WhiteBalance, 'Y' => $tm[0], 'y' => $tm[1], ); my $thename = ""; my $substroffset = 0; my $substrchar; my $tag_to_name_val = ""; my $tag_to_name = ""; dbgmsg (4, "'$template' (length: ", scalar(@templatearea), ")\n"); while ($substroffset < scalar(@templatearea)) { $substrchar = $templatearea[$substroffset++]; if ($substrchar eq "%" and $substroffset < scalar(@templatearea)) { $substrchar = $templatearea[$substroffset++]; if (defined $templatehash{$substrchar}) { $thename .= $templatehash{$substrchar}; } } elsif ($substrchar eq "#" and $substroffset < scalar(@templatearea)) { $substrchar = $templatearea[$substroffset++]; until ($substrchar eq "#") { $tag_to_name .= $substrchar; $substrchar = $templatearea[$substroffset++]; } if (defined $infoObj->{$tag_to_name}) { $tag_to_name_val = $infoObj->{$tag_to_name}; dbgmsg (2, "Tag '$tag_to_name' = $tag_to_name_val\n"); $tag_to_name_val =~ s/[\s()]//g; $tag_to_name_val =~ s/[\/\\:;\'\"]/_/g; $thename .= $tag_to_name_val; } $tag_to_name_val = $tag_to_name = ""; } else { $thename .= $substrchar; } } return $thename; } ######################################################################################## # # MAIN() renames and rotates given files # getOptions(); parseConfig($configFile); switchColor(); # redefining options set in configuration file with set via CLI ones $cfgOpts{'aggregation delta'} = $aggrDelta if (defined $aggrDelta); $cfgOpts{'aggregation directory'} = $aggrDir if (defined $aggrDir); $cfgOpts{'aggregation mode'} = $aggrMode if (defined $aggrMode); $cfgOpts{'aggregation template'} = $aggrTemplate if (defined $aggrTemplate); $cfgOpts{'aggregation virtual'} = $aggrVirtual if (defined $aggrVirtual); $cfgOpts{'keywordize'} = $keywordize if (defined $keywordize); $cfgOpts{'keywords file'} = $keywordsFile if (defined $keywordsFile); $cfgOpts{'keywords replace'} = $keywordsReplace if (defined $keywordsReplace); $cfgOpts{'mtime'} = $mtime if (defined $mtime); $cfgOpts{'name template'} = $nameTemplate if (defined $nameTemplate); $cfgOpts{'trim'} = $trim if (defined $trim); $cfgOpts{'use color'} = $useColor if (defined $useColor); $cfgOpts{'use ipc'} = $useIPC if (defined $useIPC); $cfgOpts{'contact sheet'} = $contactSheet if (defined $contactSheet); $cfgOpts{'contact sheet tile'} = $contactSheetTile if (defined $contactSheetTile); $cfgOpts{'contact sheet title'} = $contactSheetTitle if (defined $contactSheetTitle); $cfgOpts{'contact sheet file'} = $contactSheetFile if (defined $contactSheetFile); $cfgOpts{'contact sheet dir'} = $contactSheetDir if (defined $contactSheetDir); $cfgOpts{'contact sheet background'} = $contactSheetBg if (defined $contactSheetBg); $cfgOpts{'contact sheet bordercolor'} = $contactSheetBd if (defined $contactSheetBd); $cfgOpts{'contact sheet mattecolor'} = $contactSheetMt if (defined $contactSheetMt); $cfgOpts{'contact sheet fill'} = $contactSheetFl if (defined $contactSheetFl); $cfgOpts{'contact sheet font'} = $contactSheetFn if (defined $contactSheetFn); $cfgOpts{'contact sheet label'} = $contactSheetLb if (defined $contactSheetLb); $cfgOpts{'contact sheet frame'} = $contactSheetFr if (defined $contactSheetFr); $cfgOpts{'contact sheet pointsize'} = $contactSheetPntSz if (defined $contactSheetPntSz); $cfgOpts{'contact sheet shadow'} = $contactSheetShadow if (defined $contactSheetShadow); $cfgOpts{'contact sheet thm fill'} = $contactSheetThmFl if (defined $contactSheetThmFl); $cfgOpts{'contact sheet thm font'} = $contactSheetThmFn if (defined $contactSheetThmFn); $cfgOpts{'contact sheet thm grad fr'} = $contactSheetThmGrFr if (defined $contactSheetThmGrFr); $cfgOpts{'contact sheet thm grad to'} = $contactSheetThmGrTo if (defined $contactSheetThmGrTo); $cfgOpts{'contact sheet thm text'} = $contactSheetThmText if (defined $contactSheetThmText); $cfgOpts{'contact sheet rank'} = $contactSheetRank if (defined $contactSheetRank); $cfgOpts{'contact sheet rank file'} = $contactSheetRankFile if (defined $contactSheetRankFile); # Remove this variable before any screen output delete $ENV{ANSI_COLORS_DISABLED} if ($cfgOpts{'use color'} != 0); dbgmsg (1, "Show what would have been happened (no real actions).\n") if ($dryRun != 0); # Validate aggregation mode possible values if (not grep (/^$cfgOpts{'aggregation mode'}$/, ('none', 'delta', 'template'))) { warnmsg ("Aggregation mode isn't correct!\n"); } # Calculate ExifTool's verbosity my $exiftoolVerbose = ($verbose > $maxVerbosity) ? ($verbose - $maxVerbosity) : 0; # ExifTool object configuration my $exifTool = new Image::ExifTool; $exifTool->Options(Binary => 1, Unknown => 1, DateFormat => '%Y%m%d%H%M%S', Verbose => $exiftoolVerbose); chdir ($workDir) || ( fatalmsg ("Can't enter to $workDir!\n"), die_renrot() ); if ($subFileSet eq "") { # All things in ARGV will be treated as file names to process @files = @ARGV; } else { dbgmsg (2, "Reading file names for processing from file: $subFileSet\n"); @files = getFileDataLines($subFileSet); chomp(@files); } # if no file is given if (scalar(@files) == 0) { my $fileMask = "*" . $extToProcess; @files = grep { -f } glob ($fileMask); } # independently of @files initialization doing this my @filenames = (); foreach my $file (@files) { next if (not -f $file); # skip absent file or not a file next if (grep {/^$file$/} @excludeList); # skip excluded file push (@filenames, $file); } # No file to process? if (scalar(@filenames) == 0) { fatalmsg ("No files to process!\n"); exit 1; } # Parse configuration file tag set foreach my $cKey (keys %cfgOpts) { next if ($cKey !~ m/^tag(file)?#\d+#\d+$/); # skip not a tag or tagfile my %tag = strToHash($cfgOpts{$cKey}); foreach my $key (keys %tag) { $tags{$key} = $tag{$key}; if ($cKey =~ m/^tagfile/) { dbgmsg (4, "Read data from '$tags{$key}{value}' for '$key'\n"); $tags{$key}{value} = getFileData($tags{$key}{value}); } } } # Put command line arguments to appropriate tags $tags{'Comment'} = {value => getFileData($comfile)} if (defined $comfile); $tags{'UserComment'} = {value => $userComment} if (defined $userComment); # Merge tags from configuration file with command line arguments map { $tags{$_} = $tagsFromCli{$_} } keys %tagsFromCli; # Print parsed tags at debug level my @dbgTags = (); foreach my $key (sort (keys %tags)) { my $group = defined $tags{$key}{group} ? $tags{$key}{group} : ""; my $value = defined $tags{$key}{value} ? $tags{$key}{value} : ""; push (@dbgTags, "$key [$group] = $value"); } dbgmsg (4, "Tags:\n", join("\n", @dbgTags), "\n") if (scalar(@dbgTags) > 0); # Validate angle value if ((defined $rotateAngle and not grep(/^$rotateAngle$/, keys %rotangles)) or (defined $rotateThumbnail and not grep(/^$rotateThumbnail$/, keys %rotangles))) { fatalmsg ("Angle should be 90, 180 or 270!\n"); exit 1; } @files = sort @filenames; dbgmsg (4, "Pushed files(", scalar(@files), "):\n", join("\n", @files), "\n"); # Preparing the variable, which contains the format of the counter output my $counterSize; if ($countFF != 0) { my $size = length((scalar(@filenames) - 1) * $countStep + $countStart); $counterSize = "%." . $size . "d"; dbgmsg (1, "Counter size: $size (amount files in cache: ", scalar(@filenames), ")\n"); } else { $counterSize = "%d"; } renRotProcess($exifTool, $counterSize); contactSheetGenerator($exifTool) if ($isThereIM); aggregationProcess($exifTool, $counterSize); __END__ =head1 NAME renrot - rename and rotate images according EXIF data =head1 SYNOPSIS renrot [OPTIONS] [[B<-->] FILE1 FILE2 ...] =head1 DESCRIPTION B is intended to work with a set of files containing EXIF data and can do two things to them -- rename and rotate. A set of files can be given either explicitly or using the B<--extension> option, which select the files with the given suffix. B operates on files in current working directory, unless given the B<--work-directory> option, which changes this default. B renames input files using a flexible name template (which, among others, uses DateTimeOriginal and FileModifyDate EXIF tags, if they exist, otherwise names the file according to the current timestamp). Further, B can aggregate files according to the shooting time period or to a given template. Additionally, it rotates files and their thumbnails, as per Orientation EXIF tag. If that tag is absent, the program allows to set rotation parameters using B<--rotate-angle> and B<--rotate-thumb> command line options. This is currently implemented only for JPEG format. The program can also place commentaries into the following locations: =over - Commentary tag from file (see B<--comment-file> option) - UserComment tag from configuration variable (see L section) =back Personal details may be specified via XMP tags defined in a configuration file, see L section. In addition, B can aggregate all files in different directories, according to a given date/time pattern template, set with B<--aggr-template>. =head1 OPTIONS =over =item B<-c> or B<--config-file> F Path to the configuration file. =item B<-d> or B<--work-directory> F Define the working directory. =item B<--exclude> F Specify files to exclude. Wildcards are not allowed. If a set of files is given, there must be as many occurrences of this option as there are files in the set. =item B<--sub-fileset> F Get names of files to operate upon from F. The file must contain a file name per line. This option is useful when you need to process only a set of X from Y files in the directory. If specified, the rest of files given in the command line is ignored. =item B<-e> or B<--extension> I Process the files with given I (JPG, jpeg, CRW, crw, etc). Depending on the operating system, the extension search might or might not be case-sensitive. =item B<-n> or B<--name-template> I section. Interpreted sequences are: =over B<%%> a literal % B<%#> a literal # B<%C> Numeric part of the original file name. Implemented for the sake of cameras, that do not supply FileNumber EXIF tag (currently all makes, except I). Such cameras generate file names starting with letters and ended with digits. No other symbols are allowed in file names, except C<->, C<.> and C<_>. B<%c> Ordinal number of file in the processed file set (see also B<--counter-fixed-field> option). B<%d> Day of month (01-31). B<%E> The value of ExposureTime tag, if defined. B<%e> Old file extension B<%F> The value of FNumber tag, if defined. B<%H> Hour (00-23). B<%I> The value of ISO tag, if defined. B<%i> FileNumber tag if exists (otherwise, it is replaced by string C). B<%M> Minute (00-59). B<%m> Month (01-12). B<%n> Previous filename (the one before B started processing). B<%O> Base part of the original filename (see B<%o>). In other words, the first part from the beginning to the last dot character. B<%o> The name file had before it was processed by B for the first time. If the file was processed only once, the tag RenRotFileNameOriginal is set to the original file name. B<%S> Second (00-59) B<%W> The value of WhiteBalance tag, if defined. B<%Y> Year with the century (1900, 1901, and so on) B<%y> Year without a century (00..99) You can use value of any EXIF tag to be included as name part. To do that you need to embrace tag name with sign B<"#">, while building name template (see L). Be careful, since any binary EXIF (like ThumbnaiImage) can produce totally unexpected results. =back =item B<--no-rename> Do not rename files (default is to rename them to YYYYmmddHHMMSS.ext) =item B<--counter-fixed-field>, B<--no-counter-fixed-field> Set fixed length for file counter, used in file name templates (see B<%c>). It is enabled by default. Use B<--no-counter-fixed-field> to undo its effect. =item B<--counter-start> I Initial value for the file counter (default is I<1>) =item B<--counter-step> I Step to increment file counter with (default is I<1>) =item B<-r> or B<--rotate-angle> I Define the angle to rotate files and thumbnails. Allowed values for I are 90, 180 or 270. It is useful for files not having Orientation tag. =item B<--rotate-thumb> I Rotate only thumbnails. Allowed values for I are 90, 180 or 270 degrees. Use if the files which were already rotated, but their thumbnails were not. =item B<--only-orientation> Rotate by changing the value of Orientation tag, no real rotation will be made. The sequence of values to rotate an image from normal (0 degrees) by 90 degrees clockwise is: 0 -> 90 -> 180 -> 270 -> 0. It means. set Orientation tag to 90cw after the first rotation, and increase that value by 90 each time the rotation is applied. For 270cw the rotation algorithm uses the reverted sequence. Rotation by 180cw triggers values in two pairs: 0 <-> 180 and 90 <-> 270. This option cannot be applied to mirror values of Orientation tag. =item B<--trim>, B<--no-trim> Pass the C<-trim> option to L, to trim if needed. By default, trimming is enabled. Use B<--no-trim> to disable it. =item B<--no-rotate> Do not rotate images (default is to rotate according to EXIF data). =item B<--mtime>, B<--no-mtime> Defines whether to set the file's mtime, using DateTimeOriginal tag value. Use B<--no-mtime> to set it to current time stamp after processing. =item B<--no-renrot> or B<--nochg> Do not rename, rotate, tag and mtime images. It saves files from any changes while allows to do aggregation, contact sheet generation e.t.c. =item B<--keywordize>, B<--no-keywordize> Whether to keywordize. Default is to not. Be careful, since with this option enabled, the existing keywords are rewriten. The keywords are taken from F<.keywords> file or file specified with option B<--keywords-file>. =item B<-k> or B<--keywords-file> F Path to the file with keywords. Its format is a keyword per line. The CR and LF symbols are removed. Empty (only whitespace) lines are ignored. Any leading and trailing whitespace is removed. For example, the line C< _Test_ CRLF> is read as C<_Test_>. =item B<--keywords-replace>, B<--no-keywords-replace> Replace existing Keywords tag list rather than add new values to it. Default is not to replace. =item B<--aggr-mode> I Run aggregation process in given I. Possible values are: none, delta or template. =item B<--aggr-delta> I Aggregation time delta, in seconds. Files with DateTimeOriginal and ones of the previous file delta, greater than B<--aggr-delta> are placed in the directories, with the names are constructed by concatenating the value of the B<--aggr-directory> option and the directory name counter. =item B<--aggr-directory> F Aggregation directory name prefix (default is I), have to be on the same file system (or on the file system which supports symbolic links in case of virtual aggregation), relative to the current working directory or an absolute path. =item B<-a> or B<--aggr-template> I section. =item B<--aggr-virtual>, B<--no-aggr-virtual> Defines virtualization for existent aggregation modes. The main effect of B<--aggr-virtual> is that any files to be aggregated remain untouched in their places, and relative symbolic links pointing to them are stored in the directory tree created. Use B<--no-aggr-virtual> to prevent virtualization. =item B<--comment-file> F File with commentaries. It is a low priority alias to I. =item B<--user-comment> I A low priority alias to I<--tag UserComment: STRING> =item B<-t> or B<--tag> I See the section L, for the detailed description =item B<--no-tags> No user's defined tags will be written. =item B<--use-color>, B<--no-use-color> Colorize output. This does NOT work under Windows. =item B<--dry-run> Do not do anything, only print would have been done. =item B<-g> or B<--generate-thumb> Generation and writing ThumbnailImage tag. The original value of the ThumbnailImage tag remains intact. To rewrite it you need to delete it first (look exiftool examples). =item B<--use-ipc>, B<--no-use-ipc> Rotate thumbnails using pipe, rather than files. This does NOT work under Windows. =item B<-v> Increase debugging level by 1. Debugging levels from 1 to 4 are internal levels, the levels from 5 till 9 are equivalent to levels 1-5 levels ExifTool with the maximum verbosity for B. =item B<-?> or B<--help> Display short usage summary and exit. =item B<--version> Output version information and exit. =back =head1 B =item B<--contact-sheet>, B<--no-contact-sheet> or B<--cs>, B<--no-cs> Create the contact sheet. Currently it works with ThumbnailImage EXIFs and the files defined as thumbnails (see the option B<--contact-sheet-thm>, below) =item B<--contact-sheet-file> or B<--cs-file> F Base file name for montage files. =item B<--contact-sheet-dir> or B<--cs-dir> F Temporary directory for montage (created in the begining and deleted at the end of the process) =item B<--contact-sheet-thm> or B<--cs-thm> Files for the montage are already thumbnails =over Options bellow are native ImageMagic montage options look ImageMagick documentation for montage options: I and I Note please, for I use RGB triplets only like I<000> for the I or I for the I. =back =item B<--contact-sheet-tile> or B<--cs-tile> I Tile MxN (IM: -tile) =item B<--contact-sheet-title> or B<--cs-title> I Set the title of the contact sheet (IM: -title). =item B<--contact-sheet-bg> or B<--cs-bg> I Background color (IM: -background). =item B<--contact-sheet-bd> or B<--cs-bd> I Border color (IM: -bordercolor). =item B<--contact-sheet-mt> or B<--cs-mt> I Frame color (IM: -mattecolor). =item B<--contact-sheet-fn> or B<--cs-fn> I Render text with this font (IM: -font). =item B<--contact-sheet-fl> or B<--cs-fl> I Color to fill the text (IM: -fill). =item B<--contact-sheet-lb> or B<--cs-lb> I Assign a label to an image (IM: -label). =item B<--contact-sheet-fr> or B<--cs-fr> I Surround image with an ornamental border in N pixels (IM: -frame). =item B<--contact-sheet-pntsz> or B<--cs-pntsz> I Font point size (IM: -pointsize). =item B<--contact-sheet-shadow> or B<--cs-shadow> Set the shadow beneath a tile to simulate depth (IM: -shadow). =item B<--contact-sheet-thm-fl> or B<--cs-thm-fl> I Color to fill the text in generated thumbnail. =item B<--contact-sheet-thm-fn> or B<--cs-thm-fn> I Render the generated thumbnail text with this font (IM: -font). =item B<--contact-sheet-thm-grfr> or B<--cs-thm-grfr> I Generated thumbnail background gradient COLOR-from =item B<--contact-sheet-thm-grto> or B<--cs-thm-grto> I Generated thumbnail background gradient COLOR-to =item B<--contact-sheet-thm-text> or B<--cs-thm-text> I Generated thumbnail text =item B<--contact-sheet-rank> or B<--cs-rank> Run ranking process according to the ranks defined with B<--contact-sheet-rank-file> The result is the colored frames of the thumbnails of contact sheets. =item B<--contact-sheet-rank-file> or B<--cs-rank-file> Path to the file with ranks. Its format is a "file rankcolor" per line. Filename separated from the color by space or tabulation. =over 01.file.jpg red 02.JPG CornflowerBlue 03.jpg aquamarine 04.file.JPG green =back Only the files found in the file will be ranked. =over =head1 B