R 在浏览器中显示来自web的图像

R 在浏览器中显示来自web的图像,r,shiny,R,Shiny,我正在尝试制作一个闪亮的应用程序,从Nasa API检索图像并将其显示给用户。 虽然我设法从API下载图像并将其存储在临时文件中,但我无法在shiny应用程序中显示它,只能在本地显示。 以下是我目前的代码: library(shiny) library(httr) library(jpeg) library(RCurl) library(jsonlite) library(shinythemes) #library(imager) key<-"eH45R9w40U4mHE79ErvPWM

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

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)
库(闪亮)
图书馆(httr)
图书馆(jpeg)
图书馆(RCurl)
图书馆(jsonlite)
图书馆(shinythemes)
#图书馆(成像仪)

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

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

也许更简单的方法是嵌入图像。查看代码,它看起来像是图像的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)
库(闪亮)

ui您的解决方案有效,谢谢!我也会改变我的钥匙谢谢你也注意到了这一点。