首页 > 解决方案 > 在shinyR中显示png文件

问题描述

我正在尝试使用闪亮显示 png 文件。文件已上传但未正确显示。我已经包含了 ui 和服务器代码

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)

标签: rshiny

解决方案


您没有对输入做任何事情(如@RolandASc 所述)。相反,您正在服务器中生成一个新的 png 文件。

作为来源,您需要添加input$file1$datapath以使用已使用 UI 上传的文件,如答案中所述。

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)

编辑:我添加了一个签入observe以在应用程序首次运行时解决错误。


推荐阅读