Skip to content

Instantly share code, notes, and snippets.

@mdeboer
Created November 20, 2018 21:22
Show Gist options
  • Save mdeboer/b819eb7c06439473c9d67dbf6f428a12 to your computer and use it in GitHub Desktop.
Save mdeboer/b819eb7c06439473c9d67dbf6f428a12 to your computer and use it in GitHub Desktop.
Lightroom renaming export action
#!/usr/bin/env php
<?php
/**
* Lightroom rename export action
*
* !! Please read carefully.
*
* This script is meant to be used with Lightroom as an export action. I wrote this script because I always rename my
* files on import using a specific format. When exporting however I want to replace a portion of the filename with the
* title included in the IPTC metadata. Unfortunately Lightroom's renaming capabilities are quite poor so this script
* does the work instead.
*
* My files have the following format after importing:
*
* 20181120-200057-0099 Test.cr2
* | | | |
* | | | \
* | | \ Shoot name
* | \ Original image number
* \ Time (hour minute second)
* Date (year month day)
*
* In many cases (shooting concerts for example) it's easier to have 'Test' replaced with the actual title of the photo.
* Also I like to have the longest edge size appended so I can quickly see for what purpose it was exported, so it
* becomes:
*
* 20181120-200057-0099 Awesome Band_1200.jpg
*
* Normally you can do this within Lightroom just fine, except that the original image number is not available in the
* metadata and lightroom cannot replace parts when renaming as Photoshop can.
*
* Feel free to edit this script!
*/
if ($argc === 1) {
exit(0);
}
function logMessage(string $text, ?array $data = null)
{
if ($data !== null) {
$text = $text.' - '.json_encode($data);
}
$text = sprintf('[%s] %s', date('c'), $text);
// Comment the line below to disable logging errors.
file_put_contents(__DIR__.'/lightroom-rename.log', $text.PHP_EOL, FILE_APPEND);
}
for ($i = 1; $i < $argc; $i++) {
$dir = dirname($argv[$i]);
$file = basename($argv[$i]);
// Read size and extended info (APP markers)
$info = null;
$size = getimagesize($argv[$i], $info);
if (isset($info['APP13']) === false) {
// No metadata was found so skip.
logMessage('No APP13 metadata block found in file.', ['file' => $argv[$i]]);
continue;
}
// Read IPTC metadata
$iptc = iptcparse($info['APP13']);
// File title
$title = $iptc['2#005'][0] ?? null;
if (empty($title)) {
// Title is empty, skip renaming
logMessage('Title is empty, skipping.', ['file' => $argv[$i], 'iptc' => $iptc]);
continue;
}
// New filename (edit to match your filename structure)
$newFile = preg_replace('/([0-9]+\-[0-9]+\-[0-9]+\s).+?(\_[0-9]+)?(\.jpg)/i', sprintf('${1}%s_%d${3}', $title, max($size[0], $size[1])), $file);
// Rename
rename($argv[$i], $dir.DIRECTORY_SEPARATOR.$newFile);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment