2

I have the following data frame which can be downloaded from here. The column image_path has jpg files in base64 format. I want to extract the image and store it in a local folder. I tried using the code given here and here.

While the second one perfectly opens the image in the browser, I couldn't figure out how to save the file locally. I tried the following code:

library(shiny)
for (i in 1:length(df)){
file <- paste(df$id[i])
png(paste0(~images/file, '.png'))
tags$img(src = df$image_path[i])
dev.off()
}

The following just runs but doesn't create any image files and no errors are shown. When I tried running tags$img(src = df$image_path[1]) to see if it generates the image, it doesn't. I understand tags$img is a function within shiny and works when I pass it inside ui (as suggested by @daatali), but not sure how do I save the files locally.

What I want is to run a for loop from inside a server environment of shiny and save the images locally as jpg using id numbers as filename, which can be rendered with various other details captured in the survey.

I have never worked with images and please bear with me if this is completely novice.

Community
  • 1
  • 1
Apricot
  • 2,925
  • 5
  • 42
  • 88

1 Answers1

1

This creates your images from the base64 strings and saves the files to your current working directory, subfolder "/images/". This article describes pretty well how to save files locally in Shiny.

library(shiny)
library(base64enc)
filepath <- "images/"
dir.create(file.path(filepath), showWarnings = FALSE)
df <- read.csv("imagefiletest.csv", header=T, stringsAsFactors = F)
for (i in 1:nrow(df)){
  if(df[i,"image_path"] == "NULL"){
    next
  }
  testObj <- strsplit(df[i,"image_path"],",")[[1]][2]
  inconn <- testObj
  outconn <- file(paste0(filepath,"image_id",df[i,"id"],".png"),"wb")
  base64decode(what=inconn, output=outconn)
  close(outconn)
}

enter image description here

nilsole
  • 1,663
  • 2
  • 12
  • 28
  • Thanks a ton....Truly appreciate....Have been breaking my head over the last two days...this really helps....thank you. – Apricot Oct 09 '16 at 11:34