Satyaki Dasgupta
Satyaki Dasgupta

Reputation: 115

display png file in shinyR

I am trying to display a png file using shiny. file is uploaded but not displayed properly. I have included both ui and server code

ui <- fluidPage(
  titlePanel("Upload Slide Image"),
  sidebarLayout(
    sidebarPanel(fileInput("file1", "Choose png File", multiple = TRUE, 
  accept = c(".png")) ), # Input: Select a file ----
    mainPanel(imageOutput("myImage")) 
  )
)

server <- function(input, output, session){
  output$myImage <- renderImage({
    outfile <- tempfile(fileext = '.png')
    png(outfile, width = 400, height = 300) # Generate the PNG
    dev.off()
    list(src = outfile,contentType = 'image/png',width = 400, height = 300,
         alt = "This is alternate text")
  }, deleteFile = TRUE)
}

# Create Shiny app ----
shinyApp(ui, server)

Upvotes: 1

Views: 2361

Answers (1)

Urvah Shabbir
Urvah Shabbir

Reputation: 985

You are not doing anything with input (as mentioned by @RolandASc). Rather you are generating a new png file in your server.

As a source, you need to add input$file1$datapath to use the file that has been uploaded using the UI, as mentioned in this answer.

ui <- fluidPage(
      titlePanel("Upload Slide Image"),
      sidebarLayout(
        sidebarPanel(fileInput("file1", "Choose png File", multiple = TRUE, 
                               accept = c(".png")) ), # Input: Select a file ----
        mainPanel(imageOutput("myImage")) 
      )
    )

    server <- function(input, output, session){
      observe({
        if (is.null(input$file1)) return()
        output$myImage <- renderImage({
          ## Following three lines CREATE a NEW image. You do not need them
          #outfile <- tempfile(fileext = '.png')
          #png(outfile, width = 400, height = 300) # Generate the PNG
          #dev.off()

          list(src = input$file1$datapath, contentType = 'image/png',width = 400, height = 300,
               alt = "This is alternate text")
        }, deleteFile = TRUE)
      })
    }

    # Create Shiny app ----
    shinyApp(ui, server)

EDIT: I have added a check in observe to cater for error when the app is first run.

Upvotes: 2

Related Questions