Use magick::image_resize() to shrink an image if its width is larger than the value specified by the argument width, and optionally call tinify() to compress it.

shrink_images(
  width = 800,
  dir = ".",
  files = all_files("[.](png|jpe?g|webp)$", dir),
  tinify = FALSE
)

Arguments

width

The desired maximum width of images.

dir

The directory of images.

files

A vector of image file paths. By default, this is all .png, .jpeg, and .webp images under dir.

tinify

Whether to compress images using tinify().

Examples

f = xfun:::all_files("[.](png|jpe?g)$", R.home("doc"))
file.copy(f, tempdir())
#>  [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
f = file.path(tempdir(), basename(f))
magick::image_info(magick::image_read(f))  # some widths are larger than 300
#> # A tibble: 10 × 7
#>    format width height colorspace matte filesize density
#>    <chr>  <int>  <int> <chr>      <lgl>    <int> <chr>  
#>  1 JPEG      40     40 sRGB       FALSE     1013 72x72  
#>  2 JPEG     100     76 sRGB       FALSE    15985 300x300
#>  3 JPEG      40     40 sRGB       FALSE     1022 72x72  
#>  4 JPEG      40     40 sRGB       FALSE     1021 72x72  
#>  5 PNG      432    432 sRGB       TRUE      7185 72x72  
#>  6 PNG      559    432 sRGB       TRUE      5570 72x72  
#>  7 PNG      288    288 sRGB       TRUE      3884 72x72  
#>  8 PNG      259    331 sRGB       TRUE      3853 72x72  
#>  9 PNG      559    432 sRGB       TRUE      9376 72x72  
#> 10 PNG      432    432 sRGB       TRUE      2728 72x72  
xfun::shrink_images(300, files = f)
magick::image_info(magick::image_read(f))  # all widths <= 300 now
#> # A tibble: 10 × 7
#>    format width height colorspace matte filesize density
#>    <chr>  <int>  <int> <chr>      <lgl>    <int> <chr>  
#>  1 JPEG      40     40 sRGB       FALSE     1013 72x72  
#>  2 JPEG     100     76 sRGB       FALSE    15985 300x300
#>  3 JPEG      40     40 sRGB       FALSE     1022 72x72  
#>  4 JPEG      40     40 sRGB       FALSE     1021 72x72  
#>  5 PNG      300    300 Gray       TRUE      8132 72x72  
#>  6 PNG      300    232 Gray       TRUE      6363 72x72  
#>  7 PNG      288    288 sRGB       TRUE      3884 72x72  
#>  8 PNG      259    331 sRGB       TRUE      3853 72x72  
#>  9 PNG      300    232 Gray       TRUE      9759 72x72  
#> 10 PNG      300    300 Gray       TRUE      4466 72x72  
file.remove(f)
#>  [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE