在闪亮的 R 中显示来自网络的图像

Ala*_*anq 3 r shiny

我正在尝试制作一个从 Nasa API 检索图像并将其显示给用户的 Shiny 应用程序。尽管我设法从 API 下载图像并将其存储在临时文件中,但我无法在闪亮的应用程序中显示它,而只能在本地显示。到目前为止,这是我的代码:

library(shiny)
library(httr)
library(jpeg)
library(RCurl)
library(jsonlite)
library(shinythemes)
#library(imager)

key<-"eH45R9w40U4mHE79ErvPWMtaANJlDwNaEtGx3vLF"
url<-"https://api.nasa.gov/planetary/apod?date="


ui <- fluidPage(theme = shinytheme("yeti"),

   # Application title
   titlePanel("Nasa API"),


   sidebarLayout(
      sidebarPanel(
        helpText("Wellcome to Nasa search API ",
                            "enter a date in YYYY-MM-DD to search for picture"),
                   textInput("date", label="Date input", 
                             value = "Enter date..."),
                   actionButton("go", "Search")
      ),


      mainPanel(
        imageOutput("myImage")
      )
   )
)


server <- function(input, output,session) {

  query<-eventReactive(input$go,{
    input$date
    })


  output$myImage <- renderImage({
    nasa_url<-paste0(url,query(),"&api_key=",key)
    # A temp file to save the output.
    # This file will be removed later by renderImage
    response<-getURLContent(nasa_url)
    json<-fromJSON(response)
    img_url<-json$url
    temp<-tempfile(pattern = "file", fileext = ".jpg")
    download.file(img_url,temp,mode="wb")
    jj <- readJPEG(temp,native=TRUE)
    plot(0:1,0:1,type="n",ann=FALSE,axes=FALSE)
    rasterImage(jj,0,0,1,1)
    #im<-load.image(temp) #use this with library(imager)
    #plot(im)             #use this with library(imager)

  },deleteFile = T)
}

# Run the application 
shinyApp(ui = ui, server = server)
Run Code Online (Sandbox Code Playgroud)

Joh*_*ene 5

共享您的代码时要小心,因为您只是共享了您的私有 API 密钥。我建议你生成一个新的。

它不起作用,因为闪亮只提供目录中的~/www文件。因此,它们应该下载到该文件夹​​中,以便您的方法起作用。

也许更简单的方法是嵌入图像。查看代码,它看起来像是json$url图像的 URL。

library(shiny)

ui <- fluidPage(
  h4("Embedded image"),
  uiOutput("img")
)

server <- function(input, output, session) {
  output$img <- renderUI({
      tags$img(src = "https://www.r-project.org/logo/Rlogo.png")
  })
}

shinyApp(ui, server)
Run Code Online (Sandbox Code Playgroud)

您可以在不进行硬编码的情况下尝试上述操作https://www.r-project.org/logo/Rlogo.png,json$url而是使用您的。