在R Shiny中显示本地存储的图像

问题描述

我花了很多时间来解决这个问题。 当然,在这里分享我的问题之前,我做了功课。

尤其是我未成功咨询:

  1. local image in shiny app without img(src())?
  2. Shiny can not display Image locally
  3. adding local image with html to a Shiny app
  4. R Shiny img() on UI side does not render the image
  5. Display images from web in shiny R
  6. Image failing to display in R shiny
  7. Embedding Image in Shiny App
  8. How to place an image in an R Shiny title

所以我确实在RStudio项目文件的根目录中创建了一个'www'文件夹,并在其中放置了一些图片

titlePanel中使用了这些图片,主htmlwidget应用程序调用中也使用了这些图片

将这些图片存储在本地对我来说至关重要,因为该应用程序可能在安全的环境中运行而无法访问Internet。

我尝试了这些图片的相对路径和绝对路径:没有图片显示

然后,我注意到某种不一致的地方:仅当我通过RStudio中的常规命令“运行选定的行”运行应用程序时,才遇到此问题。 另一方面,当我通过专用命令“运行应用程序”运行应用程序时(在RStudio的右上角,绿色箭头),我不再遇到这个问题,图片显示得很好(但是输入数据是经过某种方式的检查,启动该应用程序需要花费很多时间。

最初,我认为显示本地图像要比存储在Internet上的远程图像要容易得多,但似乎反之亦然。

提出我的问题:

  1. 您知道为什么我们可以观察到这种差异(对我而言这是不一致的)吗?
  2. 您知道我如何继续使用常规执行命令(“运行选定的行”)?

最诚挚的问候,

奥利维尔

解决方法

管理目录可能很棘手。

您可以使用here软件包使处理R项目中的目录变得更加容易,请参阅Ode to the here package

打开项目后,www中的图像可以通过以下方式轻松访问:

here::here('www/myimage.jpg')

这也适用于采购应用程序或脚本。

,

对我来说,在RStudio中通过Run Selected Line(s)运行应用程序时,以下内容也适用:

library(shiny)

# create some local images
if(!dir.exists("myimages")){
  dir.create("myimages")
}

myPlotPaths <- paste0("myimages/myplot",seq_len(3),".png")

for (myPlot in myPlotPaths) {
  png(file = myPlot,bg = "transparent")
  plot(runif(10))
  dev.off() 
}

myImgResources <- paste0("imgResources/myplot",".png")

# Add directory of static resources to Shiny's web server
addResourcePath(prefix = "imgResources",directoryPath = "myimages")

ui <- fluidPage(
  tags$img(src = myImgResources[1],width = "400px",height = "400px"),tags$img(src = myImgResources[2],tags$img(src = myImgResources[3],height = "400px")
)

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

shinyApp(ui,server)
,

我没有具体的答案,但哈德利在“掌握闪亮”一书中的“图形”章节下展示了一个示例,说明如何显示本地存储的图像。这本书正在开发中,应该很快就会发布,我将粘贴该章节的链接:

Graphics chapter

示例位于图像部分。

HTH