Reputation: 44788
If I have a .PNG file, is there a simple way to display it in the RStudio viewer pane?
Using this answer https://stackoverflow.com/a/9319351/2554330 I can display it in the plot pane using
library(png)
filename <- system.file("img", "Rlogo.png", package="png") # or your own file
img <- readPNG(filename)
grid::grid.raster(img)
A complicated way to get it into the viewer pane is this:
temp <- tempfile(fileext = ".html")
writeLines(as.character(htmltools::img(src=knitr::image_uri(filename))), temp)
getOption("viewer")(temp)
but is there a simpler way? E.g. is there an existing function in some package that does this in one call, like
showPNG(filename)
? I could write my code in such a function, but I'd prefer to use someone else's code that has been tested and maybe works in a wider range of environments than just RStudio, etc.
Edited to add: I've been looking closer at the answer I accepted (because I wanted to avoid depending on the magick
package), and discovered something that surprised me: if filename
is "preview.png"
, then getOption("viewer")(filename)
will do the display in the viewer pane. magick::image_read
is flexible and handles many other cases, but for me it was basically just copying and renaming the file!
Upvotes: 9
Views: 5512
Reputation: 84519
The new version of the swipeR package provides a RStudio addin allowing to choose image files and to display them in the viewer pane. One can also visualize an animated GIF. Soon on CRAN.
Upvotes: 1
Reputation: 3175
Using the R package magick:
library(magick)
#> Linking to ImageMagick 7.0.10.26
#> Enabled features: cairo, fontconfig, freetype, lcms, pango, rsvg, webp, x11
#> Disabled features: fftw, ghostscript
#> Using 4 threads
# Assuming png package is installed.
filename <- system.file("img", "Rlogo.png", package="png")
image_read(filename)
Created on 2020-08-28 by the reprex package (v0.3.0)
Upvotes: 5