rcolorsexportrasterrgdal

R exporting raster with a color table


in one of my older scripts, I used the writeGDAL function to export a single-band integer raster image with a color table assigned to specific raster values to the disk. Now that the rgdal package has been removed from R, is there another way to achieve the same effect? The raster with saved colors needs to be a single tif file that, when opened in QGIS, will correctly and automatically assign colors to specific values. I would be very grateful for any help.

Below, I am providing a snippet of code that previously worked correctly.

r<-readGDAL("my_raster.tif")
writeGDAL(r, "my_new_raster.tif", type="Byte",
   colorTable=c("#00000000","#FF0000","#FFA500","#7FFF00","#006300","#0000ff"),
   catNames=c("class_a",'class_b','class_c','class_d', 'class_e', 'class_e'), mvFlag=0)

I tried using raster package with the r@legend slots to define values, colors, and names, e.g. r@legend@color<-c("#00000000","#FF0000","#FFA500","#7FFF00","#006300","#0000ff") but this information is not retained when exporting with writeRaster: writeRaster(r, "my_new_raster.tif", datatype='INT1U', format="GTiff", overwrite=T)


Solution

  • You can use terra::writeRaster

    library(terra)
    r <- rast(ncols=3, nrows=2, vals=1:6)
    coltab(r) <- data.frame(value=1:6, col=rainbow(6, end=.9))
    writeRaster(r, "test.tif", overwrite=TRUE, datatype="INT1U")
    
    x <- rast("test.tif")
    coltab(x)[[1]] |> head()
      value red green blue alpha
    1     0   0     0    0   255
    2     1 255     0    0   255
    3     2 235   255    0   255
    4     3   0   255   41   255
    5     4   0   194  255   255
    6     5  82     0  255   255