How to convert a raster layer to a vector "raw"

Dear community,
I have a plumber endpoint that accept a tiff file.

The plumber api should firt create the raster file and apply a simple operations.

after the operation, the raster must be convert to "raw" vector and pass this to the plumber::as_attachment() function.

I will attach the code that i have developed in order to do so, but i have a problem to convert the modified raster to "raw" vector.

#* @tag RasterOperation
#* @param raster:binary 
#* @post /RasterOperation
#* @serializer octet
function(raster){
    fn <- names(raster)
    print(fn)
    content <- raster[[1]]
    print(content)
   
    writeBin(content, con = "raster.tif")

    raster_file <- raster::raster("raster.tif")

    raster_file<-raster_file*77.447-9.0073

    unlink("raster.tif", force = T)

    writeBin(raster_file, con = "raster.tif")

    bin_raster<-readBin("raster.tif", what = "raw", n=length(content))
    
    plumber::as_attachment(bin_raster, fn)
}

Thanks to any support

Hello,

I'm not entirely sure, but I think that you need to specify the n arguments as the file size in bytes, not the length of the raster. Here is an example:

write("hello world!", "test.txt")

test = readBin("test.txt", what = "raw", n = file.size("test.txt"))

test #raw 
#>  [1] 68 65 6c 6c 6f 20 77 6f 72 6c 64 21 0d 0a
rawToChar(test) #converted back to characters
#> [1] "hello world!\r\n"

Created on 2023-02-14 with reprex v2.0.2
Hope this helps,
PJ

Thanks for your suggestions.

I modified the code and now it's working perfectly.

take a look

#* @tag RasterOperation
#* @param raster:binary 
#* @post /RasterOperation
#* @serializer octet
function(raster){
  
  fn <- names(raster)
  print(fn)
  content <- raster[[1]]
  print(content)
  
  writeBin(content, con = "raster.tif")
  
  raster_file <- raster::raster("raster.tif")
  
  raster_file<-raster_file*77.447-9.0073
  
  writeRaster(raster_file,
              overwrite=T,
              filename = "raster.tif")
  
  bin_raster<-readBin("raster.tif", what = "raw", n=file.size("raster.tif"))
  
  unlink("raster.tif", force = T)
  
  plumber::as_attachment(bin_raster, fn)
}
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.