Last active
September 30, 2018 13:52
-
-
Save tjmahr/41c3efbad40b7402b04252b9fbe439d1 to your computer and use it in GitHub Desktop.
sorting photos
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# R script for sorting the pictures in my OneDrive's camera roll folder. Photos | |
# in the directory are uploaded and backed up here automatically from the iOS | |
# OneDrive app. This script puts the photos into Year / Month subfolders. | |
dir <- "F:/Tristan/OneDrive/Pictures/Camera Roll" | |
ps <- list.files(dir, "*.(jpg|png)", full.names = TRUE) | |
library(exiftoolr) | |
library(dplyr) | |
move_photos <- function(exif_df) { | |
stopifnot(c("Year", "Month", "SourceFile") %in% names(exif_df)) | |
for (x in seq_along(exif_df$SourceFile)) { | |
row <- exif_df[x, ] | |
year_dir <- fs::path_join(c(dir, row$Year)) | |
month_dir <- fs::path_join(c(year_dir, row$Month)) | |
new_path <- fs::path_join(c(month_dir, basename(row$SourceFile))) | |
fs::file_move(row$SourceFile, new_path) | |
} | |
exif_df | |
} | |
create_date_dirs <- function(exif_df) { | |
stopifnot(c("Year", "Month", "SourceFile") %in% names(exif_df)) | |
dates <- distinct(exif_df, Year, Month) | |
for (x in seq_along(dates$Month)) { | |
row <- dates[x, ] | |
year_dir <- fs::path_join(c(dir, row$Year)) | |
month_dir <- fs::path_join(c(year_dir, row$Month)) | |
fs::dir_create(year_dir) | |
fs::dir_create(month_dir) | |
} | |
dates | |
} | |
exif <- exif_read(head(ps, 2000), c("SourceFile", "CreateDate")) %>% | |
as_tibble() | |
if (!rlang::has_name(exif, "CreateDate")) { | |
exif$CreateDate <- NA | |
} | |
# Move based on exif date | |
dated_exif <- exif %>% | |
filter(!is.na(CreateDate)) %>% | |
mutate( | |
CreateDate = lubridate::ymd_hms(CreateDate), | |
Year = lubridate::year(CreateDate), | |
Month = sprintf("%02.f", lubridate::month(CreateDate))) %>% | |
filter(!is.na(Month), !is.na(Year)) | |
create_date_dirs(dated_exif) | |
move_photos(dated_exif) | |
# If there is no exif data, try to use filename if it has format | |
# "[yyyymmdd]_[digits]_iOS" | |
no_date_exif <- exif %>% | |
filter(is.na(CreateDate)) | |
no_date_exif <- no_date_exif %>% | |
mutate( | |
File = basename(SourceFile)) %>% | |
filter(stringr::str_detect(File, "^20\\d{6}_\\d+_iOS")) %>% | |
mutate( | |
Date = File %>% stringr::str_extract("^\\d{8}") %>% lubridate::ymd(), | |
Year = lubridate::year(Date), | |
Month = sprintf("%02.f", lubridate::month(Date))) %>% | |
filter(!is.na(Month), !is.na(Year)) | |
create_date_dirs(no_date_exif) | |
move_photos(no_date_exif) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment