Skip to content
Snippets Groups Projects

Resolve "Normalize dimension of images in report"

Merged David Dorchies requested to merge 6-normalize-dimension-of-images-in-report into main
1 file
+ 7
0
Compare changes
  • Side-by-side
  • Inline
R/plot_png.R 0 → 100644
+ 43
0
#' Plot a PNG file
#'
#' @details
#' This function offers two advantages for displaying images in reports
#' or vignettes instead of markdown syntax or [knitr::include_graphics()]:
#' - The size of the image is controlled by the chunk parameters
#' - Image files stored outside the report or vignette folder are correctly
#' rendered in HTML
#'
#' @source From https://stackoverflow.com/a/28729601/5300212
#' @param path Path of the file
#' @param add [logical] Add the image to the existing plot
#'
#' @return Nothing, used to side effect.
#' @export
#'
#' @examples
#' plot_png(system.file("img", "Rlogo.png", package="png"))
plot_png <- function(path, add = FALSE) {
# read the file
pic <- png::readPNG(path, native = TRUE)
res <- dim(pic)[2:1] # get the resolution, [x, y]
if (!add) {
opar <- par(mar = c(0, 0, 0, 0))
plot(
1,
1,
xlim = c(1, res[1]),
ylim = c(1, res[2]),
asp = 1,
type = 'n',
xaxs = 'i',
yaxs = 'i',
xaxt = 'n',
yaxt = 'n',
xlab = '',
ylab = '',
bty = 'n'
)
par(opar)
}
graphics::rasterImage(pic, 1, 1, res[1], res[2], xpd = TRUE)
}
Loading