#' @export
#' @importFrom locatexec exec_available node_exec
#' @title Minify size your images
#' @description Minify size of images located in a directory
#' and output results in another folder.
#'
#' This function can only be used after executing the command
#' [compress_images_install()] which installs a set of "npm" packages
#' on your machine.
#' @param dir_input,dir_output input and output directories
#' @examples
#' # generate some png
#' from_dir <- tempfile()
#' dir.create(from_dir)
#'
#' png(file = file.path(
#' from_dir, "file_1.png"), width = 8.3, height = 11.7,
#' units = "in", res = 300)
#' barplot(1:10, col = 1:10)
#' dev.off()
#'
#' png(file = file.path(
#' from_dir, "file_2.png"), width = 8.3, height = 11.7,
#' units = "in", res = 300)
#' barplot(1:10, col = 11:20)
#' dev.off()
#'
#' library(locatexec)
#' if(exec_available("node") &&
#' compress_images_available()){
#'
#' # generate dest folder
#' new_dir <- tempfile()
#' dir.create(new_dir)
#'
#' # run compression
#' compress_images(from_dir, new_dir)
#'
#' desc_folder <- function(dir){
#' all_files <- list.files(
#' path = dir, full.names = TRUE, recursive = TRUE)
#' data.frame(
#' basename = basename(all_files),
#' size = file.info(all_files)$size)
#' }
#'
#' desc_folder(from_dir)
#' desc_folder(new_dir)
#' }
compress_images <- function(dir_input, dir_output = NULL){
if(!dir.exists(dir_input)){
stop("dir_input does not exist")
}
dir_output <- paste0(absolute_path(dir_output), "/")
dir_input <- absolute_path(dir_input)
if(!dir.exists(dir_output)){
stop(shQuote(dir_output), " does not exist")
}
compimg_dir <- working_directory()
exec_available("node", error = TRUE)
exec_available("npm", error = TRUE)
if(!compress_images_available()){
stop("'compress-images' is not in your user data directory,",
" run `compress_images_install()` to install it")
}
old_warn <- getOption("warn")
options(warn = -1)
info <- try(
system2(
node_exec(),
args = c(
shQuote(file.path(compimg_dir, "index.js"), type = "cmd"),
shQuote(paste0(dir_input, "/**/*.{jpg,JPG,jpeg,JPEG,png,svg,gif}"), type = "cmd"),
shQuote(dir_output, type = "cmd")
),
stderr = TRUE, stdout = TRUE), silent = TRUE)
options(warn = old_warn)
out <- !1 %in% attr(info, "status")
if(!out) {
stop(paste0(info, collapse = "\n"))
}
dir_output
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.