Search code examples
rimageshinylocaldisplay

Display locally-stored image in R Shiny


I spent a fair amount of time trying to solve that issue. Of course I did my homework before sharing my issue here.

In particular I have unsuccessfully consulted :

  1. local image in shiny app without img(src())?
  2. Shiny can not display Image locally
  3. adding local image with html to a Shiny app
  4. R Shiny img() on UI side does not render the image
  5. Display images from web in shiny R
  6. Image failing to display in R shiny
  7. Embedding Image in Shiny App
  8. How to place an image in an R Shiny title

So I did create a 'www' folder at the root of the RStudio project file where I put some pictures.

These pictures are used in the titlePanel but also by the main htmlwidget the application calls.

It is crucial for me to have these pictures stored locally because the application may be running in a secured environment without any access to the Internet.

I tried a relative path to these pictures and an absolute path: no picture was displayed.

Then I noticed some kind of inconsistency: I experience this issue only when I run the application through the regular command in RStudio, "Run Selected Line(s)". On the other hand, when I run the application through the dedicated command "Run App" (in the top right corner in RStudio, green arrow), I don't have this issue anymore, the pictures display nicely (but the input data are somehow inspected and it takes a lot of time before the application is launched).

Initially I thought that displaying local images would be much easier than with remote images stored on the Internet but it seems it is rather the other way around.

Hence my questions:

  1. Do you know why we can observe this difference (which is an inconsistency to me)?
  2. And do you know how I could still continue to use the regular execution command ("Run Selected Line(s)")?

Best regards,

Olivier


Solution

  • For me the following also works when running the app via Run Selected Line(s) in RStudio:

    library(shiny)
    
    # create some local images
    if(!dir.exists("myimages")){
      dir.create("myimages")
    }
    
    myPlotPaths <- paste0("myimages/myplot", seq_len(3), ".png")
    
    for (myPlot in myPlotPaths) {
      png(file = myPlot, bg = "transparent")
      plot(runif(10))
      dev.off() 
    }
    
    myImgResources <- paste0("imgResources/myplot", seq_len(3), ".png")
    
    # Add directory of static resources to Shiny's web server
    addResourcePath(prefix = "imgResources", directoryPath = "myimages")
    
    ui <- fluidPage(
      tags$img(src = myImgResources[1], width = "400px", height = "400px"),
      tags$img(src = myImgResources[2], width = "400px", height = "400px"),
      tags$img(src = myImgResources[3], width = "400px", height = "400px")
    )
    
    server <- function(input, output, session) {
      
    }
    
    shinyApp(ui, server)