1

Aim: divide the available tabPanel into equal cells and display images in cells with Shiny, the number of cells in horizontal space (columns) can be inputted and changed by selectInput. As the number of columns changes, so does the sizes of grids and images.

Problem: how to change the (horizontal and vertical) spacing between cells? how to resize images to fit cells? how to load and display hundreds of images more efficiently with Shiny? Thank you in advance!

enter image description here

Below is the code adapted from this and this, which can display images, but has some problems mentioned before.

rm(list = ls())
library(shiny)

img_dirs <- list.files("www/image", full.names = TRUE)
# img_dirs <- img_dirs[1:10]
img_num <- length(img_dirs)


render_image <- function(img_num, input, output) {

  for (i in seq.int(img_num)) {

    local({
      ii <- i  
      output[[paste0("img_", ii)]] <- renderImage({

        list(src = img_dirs[ii],
             contentType = 'image/jpg',
             width = '50%',
             height = 'auto',
             alt = "Image failed to render")
      }, deleteFile = FALSE)
    })
  }
}


ui <- shinyUI(

  navbarPage(
    theme = shinythemes::shinytheme("cerulean"),
    title = "UU",


    tabPanel('images', 
             sidebarPanel(
               selectInput('col_num', 'Columns', c(1, 2, 3, 4, 6, 12), selected = 4)),

             mainPanel(
               uiOutput('myplots'))
    )
  )
)



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

  output$myplots <- renderUI({


    ## Construct imageOutputs
    img_out_lst <- lapply(seq.int(img_num), function(i)
      imageOutput(paste0('img_', i)))

    fluidRow(
      lapply(
        split(img_out_lst, f = rep(c(1 : as.numeric(input$col_num)), length.out = length(img_out_lst))), 
        function(x) column(width = 12 / as.numeric(input$col_num), x, offset = 0, align="center",
                           style = "padding: 0px 0px; margin-top:-2em")) # fail to decrease spacing
    )

  })
  observeEvent(img_num, render_image(img_num, input, output))
})

shinyApp(ui, server)
just_rookie
  • 873
  • 12
  • 33

0 Answers0