Shrink image filesizes with the TinyPNG API.
From the TinyPNG website: "TinyPNG uses smart lossy compression techniques to reduce the file size of your files. By selectively decreasing the number of colors in the image, fewer bytes are required to store the data. The effect is nearly invisible but it makes a very large difference in file size!"
Original: | Tinified: |
---|---|
example.png: 35.6 Kb | example_tiny.png: 10.8 Kb |
Panda emoji by Sofie Ascherl, from OpenMoji
TinieR works with .png and .jpg/.jpeg files, and can return the new image filepath to enable embedding in other image workflows/functions.
You can install the latest version of tinieR from Github with:
# install.packages("devtools")
devtools::install_github("jmablog/tinieR")
You will need an API key from TinyPNG. You can signup to get one here.
Once you have your API key, you can set it for your current R session with:
library(tinieR)
tinify_key("YOUR-API-KEY-HERE")
Be careful including your API key in any scripts you write, especially if you're going to be publicly or privately sharing those scripts with others! You might consider setting your API key instead in your .Renviron file (~/.Renviron). If you use the variable name TINY_API
in .Renviron, tinify()
should find it, and you can skip using tinify_api()
or providing an API at each call of tinify()
.
To shrink an image file's size, provide a path to the file relative to the current working directory to tinify()
:
tinify("example.png")
#> Filesize reduced by 50%:
#> example.png (20K) => example_tiny.png (10K)
#> 10 Tinify API calls this month
By default, tinify()
will create a new file with the suffix '_tiny' in the same directory as the original file.
To save a plot to a file an automatically shrink that file's size, just call petit_plot()
after the plot:
plot(mtcars$mpg, mtcars$drat)
petit_plot(filename = "mtcars")
Or, provide a ggplot plot object to petit_ggplot()
:
p <- ggplot(data = palmerpenguins::penguins,
aes(flipper_length_mm, body_mass_g)) +
geom_point(aes(color = species)
petit_ggplot(filename = "penguins", plot = p)
For details on all the options tinieR provides, see the "full walkthrough" vignette here.
To set default options for use with tinify()
, see the "setting default options" vignette.