0

I would like to modify an image (make it black and white) using plumber API. Using this code I keep on getting the error that the input file size is zero:

library(plumber)
library(magick)
#* Receive a JPEG file and convert it to black and white
 #* @param file:file
 #* @post /convert_to_bw
function(req, res, file) {
 # Read the uploaded JPEG file
 # Convert file$datapath to a string
  img <-image_read(as.character(file$datapath))  
   
  # Convert the image to black and white
  bw_img <- img %>% image_convert(type = "Grayscale", colorspace = "gray")
  
  # Save the black and white image to a temporary file
  tmp_file <- tempfile("bw_image_", tmpdir = ".", fileext = ".png")
  image_write(bw_img, path = tmp_file, format = "png")
  
  # Return the black and white image as a response
  res$setHeader("Content-Type", "image/png")
  res$setHeader("Content-Disposition", paste0('attachment; filename="', "bw_", tools::file_path_sans_ext(file$filename), '.png"'))
  readBin(tmp_file, "raw", n = file.size(tmp_file))
}

Any idea how to solve that?

  • Have you tried using `include_file()`? Might be easier. https://stackoverflow.com/questions/44185675/get-file-through-api-call-r-plumber – Nick ODell May 16 '23 at 22:18

0 Answers0