Search code examples
polygoncroprastergeotiff

Crop raster files with Polygon and writing the output with the same filename


i have a lot of rasterfiles (satellite images, all available in geotiff .tif extension). Some files are splitted into all bands as single files, some files have multiple bands. As this uses a lot of space on my harddrive, i want to crop every file with the area of my interest, which i have as a shapefile polygon.

I am close to my own solution and get the cropped images as new .tif files with the following code:

library(raster)
rasterfiles = list.files(path=getwd(), pattern = "*.TIF", full.names=TRUE)
s = stack(rasterfiles)
shp = readOGR("Area.shp")
rasterfiles_crop = crop(s, extent(shp))

output = writeRaster(rc, 'out.tif', format="GTiff", overwrite=TRUE, bylayer = TRUE)

With this code I receive the filenames out_1.tif, out_2.tif etc...

Unfortunately the resulting files have only 1 band, so R recognizes the 1st band, only, when it comes to a multi-band TIF image.

I want to keep all bands and the original filename and just add "_crop" at the end of the new one. May someone can help me here how i have to change the code?

Thank you


Solution

  • You could write them in a loop

    library(raster)
    library(rgdal)
    
    shp <- readOGR("Area.shp")     
    
    infiles <- list.files(path=getwd(), 
                          pattern="*.TIF", 
                          full.names=TRUE)
    
    outfiles <- file.path(YourOutputPath, 
                          paste0(basename(tools::file_path_sans_ext(infiles)),
                          "_crop.tif")
                          )
    
    for (i in seq_along(infiles)) {
      r <- crop(raster(infiles[i]), shp)
      writeRaster(r, filename=outfiles[i])
    }