1
|
|
#' Upload an image to imgur.com
|
2
|
|
#'
|
3
|
|
#' This function uses the \pkg{httr} package to upload a image to
|
4
|
|
#' \url{https://imgur.com}, and parses the XML response to a list with
|
5
|
|
#' \pkg{xml2} which contains information about the image in the Imgur website.
|
6
|
|
#'
|
7
|
|
#' When the output format from \code{\link{knit}()} is HTML or Markdown, this
|
8
|
|
#' function can be used to upload local image files to Imgur, e.g. set the
|
9
|
|
#' package option \code{opts_knit$set(upload.fun = imgur_upload)}, so the output
|
10
|
|
#' document is completely self-contained, i.e. it does not need external image
|
11
|
|
#' files any more, and it is ready to be published online.
|
12
|
|
#' @param file Path to the image file to be uploaded.
|
13
|
|
#' @param key Client ID for Imgur. By default, this uses a client ID registered
|
14
|
|
#' by Yihui Xie.
|
15
|
|
#' @return A character string of the link to the image; this string carries an
|
16
|
|
#' attribute named \code{XML} which is a list converted from the response XML
|
17
|
|
#' file; see Imgur API in the references.
|
18
|
|
#' @author Yihui Xie, adapted from the \pkg{imguR} package by Aaron Statham
|
19
|
|
#' @note Please register your own Imgur application to get your client ID; you
|
20
|
|
#' can certainly use mine, but this ID is in the public domain so everyone has
|
21
|
|
#' access to all images associated to it.
|
22
|
|
#' @references Imgur API version 3: \url{https://apidocs.imgur.com}; a demo:
|
23
|
|
#' \url{https://yihui.org/knitr/demo/upload/}
|
24
|
|
#' @export
|
25
|
|
#' @examples \dontrun{
|
26
|
|
#' f = tempfile(fileext = '.png')
|
27
|
|
#' png(f); plot(rnorm(100), main = R.version.string); dev.off()
|
28
|
|
#'
|
29
|
|
#' res = imgur_upload(f)
|
30
|
|
#' res # link to original URL of the image
|
31
|
|
#' attr(res, 'XML') # all information
|
32
|
|
#' if (interactive()) browseURL(res)
|
33
|
|
#'
|
34
|
|
#' # to use your own key
|
35
|
|
#' opts_knit$set(upload.fun = function(file) imgur_upload(file, key = 'your imgur key'))
|
36
|
|
#' }
|
37
|
|
imgur_upload = function(file, key = '9f3460e67f308f6') {
|
38
|
0
|
if (!is.character(key)) stop('The Imgur API Key must be a character string!')
|
39
|
0
|
resp = httr::POST(
|
40
|
0
|
"https://api.imgur.com/3/image.xml",
|
41
|
0
|
config = httr::add_headers(Authorization = paste("Client-ID", key)),
|
42
|
0
|
body = list(image = httr::upload_file(file))
|
43
|
|
)
|
44
|
0
|
httr::stop_for_status(resp, "upload to imgur")
|
45
|
0
|
res = httr::content(resp, as = "raw")
|
46
|
0
|
res = if (length(res)) xml2::as_list(xml2::read_xml(res))
|
47
|
|
# Breaking change in xml2 1.2.0
|
48
|
0
|
if (packageVersion('xml2') >= '1.2.0') res <- res[[1L]]
|
49
|
0
|
if (is.null(res$link[[1]])) stop('failed to upload ', file)
|
50
|
0
|
structure(res$link[[1]], XML = res)
|
51
|
|
}
|