使用R从Google云端硬盘下载图像文件

时间:2019-01-17 04:11:20

标签: r google-sheets tidyverse google-form

我创建了一个Google表单,用于在该字段中输入数据。 Google表单中的几个字段都需要拍照。在这种情况下,它是我们从不同角度(尾巴,背部,前部等)捕获的鸟的照片。

我想知道是否可以通过将Google表单响应读入R中来下载那些图像。

这是Google表格表单中的Google表单响应:

library(tidyverse)
dat <- tribble(
  ~birdID, ~date, ~tailphoto,
189307134, '2019-01-15', 'https://drive.google.com/open?id=1SfmmmYTahcmwGnyCFuXoecn_ofXpagAr',
189307135, '2019-01-13', 'https://drive.google.com/open?id=1e4FGSK6jaLPyeu_TFGPXxSZAcv3obQMd'
)


# A tibble: 2 x 3
     birdID date       tailphoto                                                         
      <dbl> <chr>      <chr>                                                             
1 189307134 2019-01-15 https://drive.google.com/open?id=1SfmmmYTahcmwGnyCFuXoecn_ofXpagAr
2 189307135 2019-01-13 https://drive.google.com/open?id=1e4FGSK6jaLPyeu_TFGPXxSZAcv3obQMd

所以问题是如何使用每个照片列中的Google云端硬盘链接下载图像。理想情况下,我想通过乐队编号(鸟ID),日期和照片类型来命名每张照片,就像这样:

189307145_2019-01-15_tail.jpg

如果我具有文件名,则可以至少下载照片:

library(googledrive)

image = 'IMG_20190114_090554.jpg'

drive_download(file = image, path = 'bird.jpg')

问题是,似乎没有一种方法可以链接驱动器链接及其对应的文件名...

1 个答案:

答案 0 :(得分:0)

这是解决我的问题的一种方法:

# first part of link needs to look like this for downloading
 export <- 'https://drive.google.com/uc?export=download&id='

# convert all sharing links to downloading links by 1) chopping off photo ID at end of link,
# and 2) adding the export format in front of the photo ID
dat <- dat %>%
  mutate_at(vars(tailphoto), ~str_sub(., start = -33, end = -1)) %>%
  mutate_at(vars(tailphoto), ~paste0(export, .)) 
dat

我使用mutate_at是因为在我的原始数据集中,我有多种照片类型。然后,您可以使用curl_download循环下载每个图像。