通过闪亮但在外部的 renderPlot 传递图像对象

Pass image objects through shiny but outside renderPlot

我有一个闪亮的应用程序,它使用 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.

我知道当我在 observeEvent 中打印 class(myplot) 时,它 returns 一个 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)

observeEvent 不是 return 对象。使用eventReactive代替,即替换

  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 是电抗导体,它不是 returned 的值。您必须执行 active_image() 才能获得 returned 值:

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