Shiny RMarkdown无法显示本地图片但Shiny R App可正常显示的问题
解决Shiny RMarkdown中本地图片无法显示的问题
问题原因
独立Shiny App会默认将www文件夹作为资源根目录,因此直接使用/Schema_BB_NKB_real.jpg可以访问图片。但Shiny RMarkdown的运行上下文不同,根路径并非指向www文件夹,导致直接引用根路径的图片无法加载;而使用绝对路径会因为部署环境的路径差异失效。
解决方案
通过addResourcePath设置相对资源路径,将本地www文件夹映射为可访问的虚拟路径,同时修改图片引用路径:
修改后的Shiny RMarkdown代码
--- title: "text on image" author: "me" date: "2023-12-17" output: html_document runtime: shiny --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE)
library(shiny) # 将本地www文件夹映射为虚拟路径"images" addResourcePath("images", "www") # Define UI ui <- fluidPage( # Application title titlePanel("Count"), # Sidebar sidebarLayout( sidebarPanel( textInput("txt1", "Enter the text1 to display below:", value = 52) ), # Show an image with a counter mainPanel( fluidRow( column( 6, div( style = " margin-left:0%; display: inline-block; text-align: center; position: absolute; ", img( src = "images/Schema_BB_NKB_real.jpg", # 使用映射后的路径 height = 400, width = 800, style = " position: relative;" ), span(htmlOutput("default1"), style = " color: orange; font-size: 20px; font-style: bold; position: relative; text-align: center; width: 100px; top: -100px; " ) ) ) ) ) ) ) # Define server logic required to draw a histogram server <- function(input, output) { output$default1 <- renderUI({ str2 <- input$txt1 str1 <- paste("You") HTML(paste("str1:", input$txt1, sep = '<br/>')) }) } # Run the application shinyApp(ui = ui, server = server)
关键说明
addResourcePath("images", "www"):将当前项目下的www文件夹注册为虚拟路径images,这样通过images/xxx.jpg就能访问www里的图片,无论是本地运行还是部署到服务器,只要www文件夹和RMarkdown文件同目录,路径就会生效。- 图片引用路径从
/Schema_BB_NKB_real.jpg改为images/Schema_BB_NKB_real.jpg,避免依赖根路径的上下文差异。
内容的提问来源于stack exchange,提问作者margon0815
相关产品推荐
相关产品推荐

