Search code examples
rshinyshinydashboard

R shinydashboard fit image into box element


I have a Shiny dashboard App that is rendering a image based on a filter, so depending on the chosen value in a filter an image is displayed inside a box. However some images are too big and are rendered outside of the box, meaning the box is not containing the the whole image.

If I try to display the same image with img(src="imagename", height = 200) the image is automatically fitted into the box. How can I replicate the same but with the imageOutput() function?

Here a snippet of how the code looks like:

library("shiny")
library("shinydashboard")

sidebar <- dashboardSidebar()

body <- dashboardBody(
    fluidRow(
        box(imageOutput("image")) # IMAGE TOO BIG AND BOX CANNOT COMPLETELY CONTAIN IT
        img(src="imagename", height = 200) # Image adjusted to box size

    )
)


ui <- dashboardPage(dashboardHeader(title = "Example"),
                    sidebar,
                    body
)

server <- function(input, output) {

 output$image <- renderImage({

    filename <- normalizePath(file.path(paste('www/',imagename, '.png', sep='')))
        list(src = filename)},
        deleteFile = FALSE)
}) 
}

shinyApp(ui, server)

Solution

  • You can set the height in the list you return with renderImage:

    output$image <- renderImage({
      filename <- normalizePath(file.path(paste0('www/', imagename, '.png')))
      list(
        src = filename, 
        height = 200
      )
    }, deleteFile = FALSE)