Created
June 18, 2024 02:03
-
-
Save smasongarrison/5ed9ab5e9fd801aef437a0fe87078037 to your computer and use it in GitHub Desktop.
This file contains 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
--- | |
title: "R Notebook" | |
output: html_notebook | |
editor_options: | |
chunk_output_type: inline | |
--- | |
```{r} | |
install.packages(c("magick", "fs", "purrr", "dplyr")) | |
``` | |
```{r} | |
library(magick) | |
library(fs) | |
library(purrr) | |
library(dplyr) | |
``` | |
```{r} | |
nullToNA <- function(x) { | |
if (length(x) == 0) { | |
x <- NA | |
# Handle case when x is a list | |
} else if (is.list(x)) { | |
for (i in seq_along(x)) { | |
if (is.null(x[[i]])) { | |
x[[i]] <- NA | |
} | |
} | |
} | |
return(x) | |
} | |
# Function to get image width, height, and aspect ratio | |
get_image_details <- function(image_path) { | |
image <- nullToNA(image_read(image_path)) | |
info <- nullToNA(image_info(image)) | |
width <- nullToNA(info$width) | |
height <- nullToNA(info$height) | |
format <- nullToNA(info$format) | |
density <- nullToNA(info$density) | |
aspect_ratio <- nullToNA(width / height) | |
return(nullToNA(list(width = width, height = height, format=format, aspect_ratio = aspect_ratio, density = density))) | |
} | |
``` | |
```{r} | |
# Path to the directory containing the images | |
image_directory <- "E:/Dropbox/Resource/Wallpapers/4k" | |
# List all image files in the directory | |
image_files <- dir_ls(image_directory, type="file",glob="*.jpeg|*.jpg|*.png|*.jfif") | |
# Calculate aspect ratios and classify them | |
image_data <- tibble(file = image_files) %>% | |
head(n=250) %>% | |
mutate(details = map(file, get_image_details), | |
width = map_dbl(details, "width"), | |
height = map_dbl(details, "height"), | |
density = map_chr(details, "density"), | |
format = map_chr(details, "format"), | |
aspect_ratio = map_dbl(details, "aspect_ratio"), | |
category = case_when( | |
aspect_ratio < .8 ~ "vertical hd", | |
aspect_ratio < 1.1 ~ "square hd", | |
TRUE ~ "landscape" | |
)) | |
# Create subfolders based on categories | |
unique(image_data$category) %>% | |
walk(~ dir_create(file.path(image_directory, .))) | |
# Move files into the corresponding subfolders | |
walk2(image_data$file, image_data$category, ~ file_move(.x, file.path(image_directory, .y, fs::path_file(.x)))) | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment