r - 在 Shiny 的 R 中显示来自网络的图像

标签 r shiny

我正在尝试制作一个从 Nasa API 检索图像并将其显示给用户的 Shiny 应用程序。 尽管我设法从 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)

最佳答案

分享您的代码时要小心,因为您刚刚分享了您的私有(private) API key 。我建议你生成一个新的。

它不起作用,因为 shiny 只提供 ~/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)

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

关于r - 在 Shiny 的 R 中显示来自网络的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53147225/

相关文章:

R Shiny : Write looped reactive inputs to textfile

r - 如何使用 future 数据框中的列

mysql - 如何让 Shiny 的应用程序与云关系数据库(在 MySQL 中)对话?

css - Shiny :标签位置,文本输入

可重现的示例和输出错误

r - 为什么roxygen2不能自动更新DESCRIPTION文件中的 “Imports”?

R:按列中最常见的值对数据进行排序

macos - 安装 Cairo R 包时出错

动态渲染 R Shiny 框中的标题

r - 在 Shiny 的 R 中更改默认浏览器