Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image slideshow in R Shiny

I am still learning R and thus would request the experts in this platform to help me out.

I am trying to create a slideshow of .jpg images in a panel in Shiny. The below code when I run in RStudio gives me the slideshow in the Plot window of RStudio.

folder <- "D:/Photos/Foreign Trips/2014_07_08_USA_Irvine/JulyAugust/" 
file_list <- list.files(path=folder, pattern="*.jpg", full.names = TRUE)
for (j in 1:30) {
        myJPG <- stack(file_list[[j]])
        plotRGB(myJPG)
}

But, when I try to put the same code in server.R and try to call through ui.R, I don't get the slideshow or any image getting displayed. I am getting a blank page when I click on the tab "Photo Slides". I tried using renderUI, renderImage and renderPlot but none works.

ui.R

tabPanel("Photo Slides",
plotOutput("trvImg")
),

server.R

output$trvImg <- renderPlot({
folder <- "D:/Photos/Foreign Trips/2014_07_08_USA_Irvine/JulyAugust/" 
file_list <- list.files(path=folder, pattern="*.jpg", full.names = TRUE)
for (j in 1:30) {
myJPG <- stack(file_list[[j]])
plotRGB(myJPG)
}

As a learner, I am sure I'm going wrong somewhere and thus seek your help.

Thanks

like image 314
Parag Avatar asked Dec 01 '22 10:12

Parag


1 Answers

library(shiny)

imgs <- list.files("D:/Photos/Foreign Trips/2014_07_08_USA_Irvine/JulyAugust/", pattern=".png", full.names = TRUE)

ui <- fluidPage(

  titlePanel("Slideshow"),

  sidebarLayout(
    sidebarPanel(
      actionButton("previous", "Previous"),
      actionButton("next", "Next")
    ),

    mainPanel(
      imageOutput("image")
    )
  )
)

server <- function(input, output, session) {

  index <- reactiveVal(1)

  observeEvent(input[["previous"]], {
    index(max(index()-1, 1))
  })
  observeEvent(input[["next"]], {
    index(min(index()+1, length(imgs)))
  })

  output$image <- renderImage({
    x <- imgs[index()] 
    list(src = x, alt = "alternate text")
  }, deleteFile = FALSE)
}

# Run the application 
shinyApp(ui = ui, server = server)

If you want the buttons below the image, you can do:

  sidebarLayout(
    sidebarPanel(
      # actionButton("previous", "Previous"),
      # actionButton("next", "Next")
    ),

    mainPanel(
      imageOutput("image"),
      fluidRow(
        column(1, offset=1, actionButton("previous", "Previous")),
        column(1, offset=1, actionButton("next", "Next"))
      )
    )
  )
like image 51
Stéphane Laurent Avatar answered Dec 04 '22 00:12

Stéphane Laurent