firmo23
firmo23

Reputation: 8404

How can I browse and upload an image in a shiny application?

I want to create a shiny application which will the user the ability to browse and load an image and then display it. My question is whether this is supported by shiny.

#ui.r
pageWithSidebar(
  headerPanel('Image Recognition'),
  sidebarPanel(
    fileInput("file1", "Choose Image",
              accept = c(
                ".jpg")
    ))
   ,
  mainPanel(
    imageOutput("file1")
  )
)
#server.r
library(shiny)

function(input, output, session) {
(shiny.maxRequestSize=30*1024^2) 

  output$myImage <- renderImage({
    # A temp file to save the output.
    # This file will be removed later by renderImage
    file1 <- tempfile(fileext = '.png')

    # Generate the PNG
    png(file1, width = 400, height = 300)
    dev.off()

    # Return a list containing the filename
    list(src = file1,
         contentType = 'image/png',
         width = 400,
         height = 300,
         alt = "This is alternate text")
  }, deleteFile = TRUE)



}

Upvotes: 2

Views: 2607

Answers (1)

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84529

Here is a solution using base64 encoding of the uploaded file.

library(shiny)
library(base64enc)

options(shiny.maxRequestSize = 30*1024^2)

ui <- fluidPage(
  fileInput("upload", "Upload image", accept = "image/png"),
  uiOutput("image")
)

server <- function(input, output){

  base64 <- reactive({
    inFile <- input[["upload"]]
    if(!is.null(inFile)){
      dataURI(file = inFile$datapath, mime = "image/png")
    }
  })

  output[["image"]] <- renderUI({
    if(!is.null(base64())){
      tags$div(
        tags$img(src= base64(), width="100%"),
        style = "width: 400px;"
      )
    }
  })
}

shinyApp(ui, server)

enter image description here

Upvotes: 6

Related Questions