0

我有一个闪亮的应用程序,它使用fileInputmagick读取用户选择的图像,并将其显示为 ggplot。

library(shiny)
library(magick)
library(ggplot2)

ui <- fluidPage(


   titlePanel(""),


   sidebarLayout(
      sidebarPanel(
        fileInput("current_image", "Choose image file")),


      mainPanel(
        plotOutput("current_image_plot")
      )
   )
)


server <- function(input, output) {

  output$current_image_plot <- renderPlot({
    req(input$current_image)
    myplot <- magick::image_read(input$current_image$datapath)
    myplot <- image_ggplot(myplot)
    return(myplot)
})
}

shinyApp(ui = ui, server = server)

但是,我想将读取图像的逻辑与绘制图像的逻辑分开。我尝试将image_read其放入内部observeEvent,但这引发了错误The 'image' argument is not a magick image object.

我知道当我class(myplot)在 中打印时observeEvent,它会返回一个magick-image对象,那么在我尝试访问时发生了什么变化active_image

library(shiny)
library(magick)
library(ggplot2)

ui <- fluidPage(


   titlePanel(""),

   sidebarLayout(
      sidebarPanel(
        fileInput("current_image", "Choose image file")),


      mainPanel(
        plotOutput("current_image_plot")
      )
   )
)


server <- function(input, output) {

  active_image <- observeEvent(input$current_image, {
    req(input$current_image)
    myplot <- magick::image_read(input$current_image$datapath)
    return(myplot)
  })

  output$current_image_plot <- renderPlot({
    req(input$current_image)
    myplot <- image_ggplot(active_image)
    return(myplot)
})
}

shinyApp(ui = ui, server = server)
4

1 回答 1

0

AnobserveEvent不返回对象。使用eventReactiveinstaed,即替换

  active_image <- observeEvent(input$current_image, {
    req(input$current_image)
    myplot <- magick::image_read(input$current_image$datapath)
    return(myplot)
  })

  active_image <- eventReactive(input$current_image, {
    req(input$current_image)
    myplot <- magick::image_read(input$current_image$datapath)
    return(myplot)
  })

或更简洁地说:

  active_image <- eventReactive(input$current_image, {
    req(input$current_image)
    magick::image_read(input$current_image$datapath)
  })

现在,active_image是一个反应导体,它不是返回的值。您必须执行以下操作active_image()才能获取返回值:

  output$current_image_plot <- renderPlot({
    req(input$current_image)
    image_ggplot(active_image())
  })
于 2020-04-06T08:11:13.503 回答