Learn R Programming

xfun (version 0.48)

tinify: Use the Tinify API to compress PNG and JPEG images

Description

Compress PNG/JPEG images with api.tinify.com, and download the compressed images. These functions require R packages curl and jsonlite. tinify_dir() is a wrapper function of tinify() to compress images under a directory.

Usage

tinify(
  input,
  output,
  quiet = FALSE,
  force = FALSE,
  key = env_option("xfun.tinify.key"),
  history = env_option("xfun.tinify.history")
)

tinify_dir(dir = ".", ...)

Value

The output file paths.

Arguments

input

A vector of input paths of images.

output

A vector of output paths or a function that takes input and returns a vector of output paths (e.g., output = identity means output = input). By default, if the history argument is not a provided, output is input with a suffix -min (e.g., when input = 'foo.png', output = 'foo-min.png'), otherwise output is the same as input, which means the original image files will be overwritten.

quiet

Whether to suppress detailed information about the compression, which is of the form input.png (10 Kb) ==> output.png (5 Kb, 50%); compression count: 42. The percentage after output.png stands for the compression ratio, and the compression count shows the number of compressions used for the current month.

force

Whether to compress an image again when it appears to have been compressed before. This argument only makes sense when the history argument is provided.

key

The Tinify API key. It can be set via either the global option xfun.tinify.key or the environment variable R_XFUN_TINIFY_KEY (see env_option()).

history

Path to a history file to record the MD5 checksum of compressed images. If the checksum of an expected output image exists in this file and force = FALSE, the compression will be skipped. This can help you avoid unnecessary API calls.

dir

A directory under which all .png, .jpeg, and .webp files are to be compressed.

...

Arguments passed to tinify().

Details

You are recommended to set the API key in .Rprofile or .Renviron. After that, the only required argument of this function is input. If the original images can be overwritten by the compressed images, you may either use output = identity, or set the value of the history argument in .Rprofile or .Renviron.

References

Tinify API: https://tinypng.com/developers.

See Also

The tinieR package (https://github.com/jmablog/tinieR/) is a more comprehensive implementation of the Tinify API, whereas xfun::tinify() has only implemented the feature of shrinking images.

Examples

Run this code
if (FALSE) { # interactive()
f = xfun:::R_logo("jpg$")
xfun::tinify(f)  # remember to set the API key before trying this
}

Run the code above in your browser using DataLab