Debian Codegraph @

R/image.R

raw
1 #' Use the Tinify API to compress PNG and JPEG images
2 #'
3 #' Compress PNG/JPEG images with \samp{api.tinify.com}, and download the
4 #' compressed images. These functions require R packages \pkg{curl} and
5 #' \pkg{jsonlite}. `tinify_dir()` is a wrapper function of `tinify()` to
6 #' compress images under a directory.
7 #'
8 #' You are recommended to set the API key in \file{.Rprofile} or
9 #' \file{.Renviron}. After that, the only required argument of this function is
10 #' `input`. If the original images can be overwritten by the compressed images,
11 #' you may either use `output = identity`, or set the value of the `history`
12 #' argument in \file{.Rprofile} or \file{.Renviron}.
13 #' @param input A vector of input paths of images.
14 #' @param output A vector of output paths or a function that takes `input` and
15 #' returns a vector of output paths (e.g., `output = `[`identity`] means
16 #' `output = input`). By default, if the `history` argument is not a provided,
17 #' `output` is `input` with a suffix `-min` (e.g., when `input = 'foo.png'`,
18 #' `output = 'foo-min.png'`), otherwise `output` is the same as `input`, which
19 #' means the original image files will be overwritten.
20 #' @param quiet Whether to suppress detailed information about the compression,
21 #' which is of the form \samp{input.png (10 Kb) ==> output.png (5 Kb, 50\%);
22 #' compression count: 42}. The percentage after `output.png` stands for
23 #' the compression ratio, and the compression count shows the number of
24 #' compressions used for the current month.
25 #' @param force Whether to compress an image again when it appears to have been
26 #' compressed before. This argument only makes sense when the `history`
27 #' argument is provided.
28 #' @param key The Tinify API key. It can be set via either the global option
29 #' `xfun.tinify.key` or the environment variable `R_XFUN_TINIFY_KEY` (see
30 #' [env_option()]).
31 #' @param history Path to a history file to record the MD5 checksum of
32 #' compressed images. If the checksum of an expected output image exists in
33 #' this file and `force = FALSE`, the compression will be skipped. This can
34 #' help you avoid unnecessary API calls.
35 #' @return The output file paths.
36 #' @references Tinify API: <https://tinypng.com/developers>.
37 #' @seealso The \pkg{tinieR} package (<https://github.com/jmablog/tinieR/>) is a
38 #' more comprehensive implementation of the Tinify API, whereas
39 #' `xfun::tinify()` has only implemented the feature of shrinking images.
40 #' @export
41 #' @examples
42 #' \dontrun{
43 #' f = xfun:::R_logo('jpg$')
44 #' xfun::tinify(f) # remember to set the API key before trying this
45 #' }
46 tinify = function(
47 input, output, quiet = FALSE, force = FALSE,
48 key = env_option('xfun.tinify.key'),
49 history = env_option('xfun.tinify.history')
50 ) {
51 if (!(is.character(key) && length(key) == 1 && key != '')) stop(
52 "The value of the 'key' argument must be a single non-empty character string."
53 )
54 if (length(input) == 0) return(invisible(input))
55 if (any(i <- !file_exists(input))) stop(
56 'Input file(s) not found: ', paste(input[i], collapse = ', ')
57 )
58 if (missing(output)) {
59 output = if (is.character(history)) input else {
60 paste0(sans_ext(input), '-min.', file_ext(input))
61 }
62 } else if (is.function(output)) output = output(input)
63
64 # avoid optimizing the input image if its md5 checksum exists in history
65 save_history = function(file) {
66 if (!is.character(history) || history == '') return()
67 dir_create(dirname(history))
68 cat(paste0(tools::md5sum(file), '\n'), file = history, append = TRUE)
69 }
70 test_history = function(file) {
71 is.character(history) && all(file_exists(c(history, file))) &&
72 (tools::md5sum(file) %in% readLines(history))
73 }
74
75 auth = paste('Authorization: Basic', base64_encode(charToRaw(paste0('api:', key))))
76
77 mapply(input, output, FUN = function(i, o) {
78 if (!force && test_history(o)) {
79 if (!quiet) message(
80 'The image ', o, ' has been compressed before. ',
81 'To compress it again, call tinify() with force = TRUE.'
82 )
83 return()
84 }
85 if (grepl('[.]png$', i, ignore.case = TRUE))
86 optipng(files = i, stdout = if (quiet) FALSE else '')
87 res = curl::curl_upload(i, 'https://api.tinify.com/shrink', httpheader = auth, verbose = FALSE)
88 cnt = curl::parse_headers_list(res$headers)[['compression-count']]
89 res = jsonlite::fromJSON(rawToChar(res$content))
90 if (!is.character(u <- res$output$url)) stop2(
91 "Failed to shrink '", i, "'", sprintf(': %s (%s)', res$error, res$message)
92 )
93 if (!quiet) message(sprintf(
94 '%s (%s) ==> %s (%s, %.01f%%); compression count: %s',
95 i, format_bytes(res$input$size), o, format_bytes(res$output$size),
96 res$output$ratio * 100, if (length(cnt)) cnt else NA
97 ))
98 # back up the original image and restore it if download failed
99 if (i == o) {
100 b = paste0(i, '~')
101 file.rename(i, b)
102 on.exit(if (file_exists(o)) file.remove(b) else file.rename(b, i), add = TRUE)
103 }
104 curl::curl_download(u, o)
105 save_history(o)
106 })
107
108 invisible(output)
109 }
110
111 #' @param dir A directory under which all \file{.png}, \file{.jpeg}, and
112 #' \file{.webp} files are to be compressed.
113 #' @param ... Arguments passed to [tinify()].
114 #' @rdname tinify
115 #' @export
116 tinify_dir = function(dir = '.', ...) {
117 tinify(all_files('[.](png|jpe?g|webp)$', dir), ...)
118 }
119
120 #' Shrink images to a maximum width
121 #'
122 #' Use [magick::image_resize()] to shrink an
123 #' image if its width is larger than the value specified by the argument
124 #' `width`, and optionally call [tinify()] to compress it.
125 #' @param width The desired maximum width of images.
126 #' @param dir The directory of images.
127 #' @param files A vector of image file paths. By default, this is all
128 #' \file{.png}, \file{.jpeg}, and \file{.webp} images under `dir`.
129 #' @param tinify Whether to compress images using [tinify()].
130 #' @export
131 #' @examplesIf xfun::loadable('magick')
132 #' f = xfun:::all_files('[.](png|jpe?g)$', R.home('doc'))
133 #' file.copy(f, tempdir())
134 #' f = file.path(tempdir(), basename(f))
135 #' magick::image_info(magick::image_read(f)) # some widths are larger than 300
136 #' xfun::shrink_images(300, files = f)
137 #' magick::image_info(magick::image_read(f)) # all widths <= 300 now
138 #' file.remove(f)
139 shrink_images = function(
140 width = 800, dir = '.', files = all_files('[.](png|jpe?g|webp)$', dir),
141 tinify = FALSE
142 ) {
143 for (f in files) {
144 x = magick::image_read(f)
145 if (magick::image_info(x)$width <= width) next
146 x = magick::image_resize(x, sprintf('%dx', width))
147 magick::image_write(x, f)
148 }
149 if (tinify) tinify(files, identity)
150 }
151
152 #' Upload an image to imgur.com
153 #'
154 #' This function uses the \pkg{curl} package or the system command `curl`
155 #' (whichever is available) to upload a image to <https://imgur.com>.
156 #'
157 #' One application is to upload local image files to Imgur when knitting a
158 #' document with \pkg{knitr}: you can set the `knitr::opts_knit$set(upload.fun =
159 #' xfun::upload_imgur`, so the output document does not need local image files
160 #' any more, and it is ready to be published online.
161 #' @param file Path to the image file to be uploaded.
162 #' @param key Client ID for Imgur. It can be set via either the global option
163 #' `xfun.upload_imgur.key` or the environment variable
164 #' `R_XFUN_UPLOAD_IMGUR_KEY` (see [env_option()]). If neither is set, this
165 #' uses a client ID registered by Yihui Xie.
166 #' @param use_curl Whether to use the R package \pkg{curl} to upload the image.
167 #' If `FALSE`, the system command `curl` will be used.
168 #' @param include_xml Whether to include the XML response in the returned value.
169 #' @return A character string of the link to the image. If `include_xml = TRUE`,
170 #' this string carries an attribute named `XML`, which is the XML response
171 #' from Imgur (it will be parsed by \pkg{xml2} if available). See Imgur API in
172 #' the references.
173 #' @author Yihui Xie, adapted from the \pkg{imguR} package by Aaron Statham
174 #' @note Please register your own Imgur application to get your client ID. You
175 #' can certainly use mine, but this ID is in the public domain and it might
176 #' reach Imgur's rate limit if too many people are using it in the same time
177 #' period or someone is trying to upload too many images at once.
178 #' @references A demo: <https://yihui.org/knitr/demo/upload/>
179 #' @export
180 #' @examples \dontrun{
181 #' f = tempfile(fileext = '.png')
182 #' png(f); plot(rnorm(100), main = R.version.string); dev.off()
183 #'
184 #' res = imgur_upload(f, include_xml = TRUE)
185 #' res # link to original URL of the image
186 #' xfun::attr2(res, 'XML') # all information
187 #' if (interactive()) browseURL(res)
188 #'
189 #' # to use your own key
190 #' options(xfun.upload_imgur.key = 'your imgur key')
191 #' }
192 upload_imgur = function(
193 file, key = env_option('xfun.upload_imgur.key'), use_curl = loadable('curl'),
194 include_xml = FALSE
195 ) {
196 if (is.null(key) || key == '' || key == '9f3460e67f308f6') {
197 i = floor(as.numeric(Sys.time()) %% 3) + 1
198 key = c("qyv(sq y 't)ws(", 'q (t"vxs%t "wr(', "xpyvq%vp'rwx)yq")[i]
199 key = decrypt(key, '1987052436fedcba')
200 }
201 api = 'https://api.imgur.com/3/image.xml'
202 hdr = paste('Authorization: Client-ID', key)
203 if (use_curl) {
204 h = curl::new_handle(httpheader = hdr)
205 curl::handle_setform(h, image = curl::form_file(file))
206 res = curl::curl_fetch_memory(api, h)$content
207 } else {
208 file = path.expand(file)
209 res = system2(
210 'curl', shQuote(c('-H', hdr, '-F', paste0('image=@', file), '-s', api)),
211 stdout = TRUE
212 )
213 res = one_string(res)
214 if (res == '') stop('Failed to upload ', file)
215 }
216 if (loadable('xml2')) {
217 res = xml2::as_list(xml2::read_xml(res))
218 link = res[[1]]$link[[1]]
219 } else {
220 if (is.raw(res)) res = rawToChar(res)
221 link = grep_sub('.*<link>([^<]+)</link>.*', '\\1', res)
222 }
223 if (length(link) != 1) stop(
224 'Failed to upload ', file, sprintf(' (reason: %s)', if (is.character(res)) {
225 grep_sub('.*<error>([^<]+)</error>.*', '\\1', res)
226 } else res[[c('data', 'error', 'message')]][[1]])
227 )
228 if (include_xml) structure(link, XML = res) else link
229 }