Display images from web in shiny R

江枫思渺然 提交于 2020-12-31 14:54:02

问题


I am trying to make a Shiny App that retrieves an image from Nasa API and displays it to the user. Although I manage to download the image from the API and store it in a temp file I can't display it in the shiny app but only locally. Here is my code so far:

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)

回答1:


Be careful when sharing your code as you just shared your private API key. I suggest you generate a new one.

It does not work because shiny only serves files that are in the ~/www directory. So they should be downloaded to that folder for your method to work.

Perhaps an easier way to go about this is simply to embed the image. Looking at the code it looks like json$url is the URL to the image.

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)

You could try the above without hardcoding https://www.r-project.org/logo/Rlogo.png and using your json$url instead.



来源:https://stackoverflow.com/questions/53147225/display-images-from-web-in-shiny-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!