-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinit_get_random_image.R
53 lines (43 loc) · 2.06 KB
/
init_get_random_image.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# Pick a random row
random_id <- sample(nrow(all_images), 1)
# Get the title and date taken. This will be used later for the ALT text in the
# Twitter image
img_title <- all_images[random_id,]$Title
img_date_taken <- all_images[random_id,]$DateTimeOriginal |> as.Date() |> as.character()
# We'll need to make one more API call to get the image URL
img_uri <- all_images$LargestImgUri[[random_id]]
# This gets us the image details that actually has the URL for the largest version of
# the image in it
img_details <- GET(url ="http://www.smugmug.com",
query = list(APIKey = sm_key),
path = img_uri,
accept_json()) %>%
content()
# Extract the actual web URL for the image
img_url <- img_details$Response$LargestImage$Url
# Get the image URL to use in the final web page. This will actually include
# the album name and make it so a user can get back to the overall SmugMug site
# more easily
img_url_rmd <- all_images$WebUri[[random_id]]
# Write the image URL details to the console (for troubleshooting)
cat("img_url:", img_url, "\n")
cat("img_url_rmd", img_url_rmd, "\n")
# Come up with the file name to save the image as. It's the filename +
# the current date + the file extension. One filename for the original and
# one filename for the transformed image
img_out_path <- paste0(rel_path, "images/",
gsub("(^.*)\\/(.*)(\\.jpg)", "\\2", img_url), "_original_",
as.character(Sys.Date()),
gsub("(^.*)\\/(.*)(\\.jpg)", "\\3", img_url))
img_trans_out_path <- gsub("original", "transformed", img_out_path)
# Download the image
img_orig <- tempfile()
download.file(img_url, img_orig, mode = "wb")
# Let's go ahead and work with "max size" of the image.
# If it's smaller than that already, fine. Otherwise, scale it down.
if(image_read(img_orig) %>% image_info() %>% .$width > max_img_width){
img_orig <- image_read(img_orig) %>% image_scale(as.character(max_img_width))
img_orig <- image_write(img_orig)
}
img_orig <- readJPEG(img_orig)
writeJPEG(img_orig, img_out_path)