Apricot Apricot - 5 months ago 40
R Question

Save base64 JPG to disk in R - Shiny

I have the following data frame which can be downloaded from here. The column

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:

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

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.


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.

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"){
  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)

enter image description here