I have a number of photos that I have put in my www folder. Is there a way to make my shiny app randomly pick and show one of them everytime the app is launched?
Sure, please check the following example app:
library(shiny)
# Create dummy images -----------------------------------------------------
img_names = paste0("img", 1:10, ".jpg")
if(!dir.exists("www")){
dir.create("www")
}
for(i in seq_along(img_names)){
png(file = paste0("www/", img_names[i]), bg = colors()[i])
par(mar = c(0,0,0,0))
plot(c(0, 1), c(0, 1), ann = F, bty = 'n', type = 'n', xaxt = 'n', yaxt = 'n')
text(x = 0.5, y = 0.5, img_names[i],
cex = 1.6, col = "black")
dev.off()
}
# Actual app --------------------------------------------------------------
ui <- fluidPage(
titlePanel("Random Image"),
mainPanel(
fluidRow(
htmlOutput("random_image_out")
)
)
)
server = function(input, output, session){
# pretending we don't know about img_names
www_imgs <- list.files(path = "www", pattern = "*.jpg$")
# random_image for each new shiny-session
random_image <- www_imgs[round(runif(1, min = 1, max = length(www_imgs)), digits = 0)]
output$random_image_out = renderUI({
tags$img(src=random_image, width="50%", height="50%")
})
}
shinyApp(ui, server)
1 Like
This works great! Thank you!
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.
If you have a query related to it or one of the replies, start a new topic and refer back with a link.