Search code examples
rshinyshinydashboardshinyappsrshiny

how to load the different image from different folder without only using www folder in the directory in the rshiny?


I am building a render image app using rshiny. I have 10 different folder and each folder has 300 image in it. I did not want to put all these 3000 image into one www folder. Is there any way I can code in the server script that I can go to the relative folder and find the right image I am looking for.

I search the rshiny official website, it said:

img(src = "my_image.png", height = 72, width = 72)

The img function looks for your image file in a specific place. Your file must be in a folder named www in the same directory as the app.R script. Shiny treats this directory in a special way. Shiny will share any file placed here with your user’s web browser, which makes www a great place to put images, style sheets, and other things the browser will need to build the wep components of your Shiny app.

I will use the rshiny website's example

library(shiny)
ui <- fluidPage(
  titlePanel("My Shiny App"),
  sidebarLayout(
    sidebarPanel(),
    mainPanel(
      img(src = "rstudio.png", height = 140, width = 400)
    )
  )
)

server <- function(input, output) {
  
}

shinyApp(ui = ui, server = server)

However, instead one image in the www folder. I have 10 different folder and each folder has 300 image in it.

I hope I can get some help. Thanks!


Solution

  • We can use renderImage() that allows to pass a folder path. Here is an example:

    library(shiny)
    
    
    ui <- fluidPage(
        titlePanel("My Shiny App"),
        sidebarLayout(
            sidebarPanel(textInput('image_path', label = 'File Path:'),
            actionButton('send_path', 'Get Image')),
            mainPanel(
                imageOutput('my_image'),
                imageOutput('my_path_image')
            )
        )
    )
    
    server <- function(input, output) {
     
        output$my_image <- renderImage({
            list(src = '~/test.png') #use ~ to acces the home folder.
        }, deleteFile = FALSE)
        
        observeEvent(input$send_path, {
            
        output$my_path_image <- renderImage({
            list(src = input$image_path) 
        }, deleteFile = FALSE)
        
        })
           
    }
    
    shinyApp(ui = ui, server = server)