1

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)



}
firmo23
  • 7,490
  • 2
  • 38
  • 114
  • beware of the path of the selected file: it is often from a misformed file path that comes a non-working chunk ;) Also, there is no `outfile` defined when you call `png()` but only `file1` – Elie Ker Arno Jun 12 '19 at 14:32
  • I used (shiny.maxRequestSize=30*1024^2) for size but it does not work. I also changed the outfile – firmo23 Jun 12 '19 at 14:59
  • What about the traceback log please? – Elie Ker Arno Jun 12 '19 at 15:07
  • It is 4.9 MB .. – firmo23 Jun 12 '19 at 15:16
  • 1
    The `shiny.maxRequestSize` is an option you need to set, not a variable you need to create. Remove that line and place `options(shiny.maxRequestSize = 30*1024^2)` just after the `library(shiny)` call in the server.R file. – MrFlick Jun 12 '19 at 15:31
  • @MrFlick I agree with firmo23. The maxRequestSize is not the main question. – Stéphane Laurent Jun 12 '19 at 16:57
  • 1
    It would make sense to edit the question to remove the file size specific error/problems. But maybe something like this would already answer the other question: https://community.rstudio.com/t/r-shiny-app-gallery-app-that-lets-user-upload-multiple-images-and-display-them-dynamically-multiple-images-like-a-grid/30288 – MrFlick Jun 12 '19 at 17:06

1 Answers1

4

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

Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225