1

I have 24 layers I want to save on QGIS which all happen to be Tiff files (rasters). I am wondering how to run code to complete this task.

myDir = 'C:\temp'
layers = layers = iface.mapCanvas().layers()
pipe = QgsRasterPipe()
for layer in layers:
   extent = layer.extent()
   width, height = layer.width(), layer.height()
   renderer = layer.renderer()
   provider=layer.dataProvider()
   crs = layer.crs().toWkt() 
   pipe.set(provider.clone())
   pipe.set(renderer.clone())
   file_writer = QgsRasterFileWriter("%s\\%s.tif" %(myDir, layer.name() ))
   file_writer.writeRaster(pipe,
                       width,
                       height,
                       extent,
                       layer.crs())

This is the code I have currently to try and run.

  • 2
    And what happens when you run it? :) – Joseph Jun 9 '17 at 12:23
  • 3
    @Joseph an error could be file_writer = QgsRasterFileWriter(myDir + layer.name() + ".tif")with a missing "\" I would use QgsRasterFileWriter("%s\\%s.tif" %(myDir, layer.name() )) instead – LaughU Jun 9 '17 at 12:27
  • 2
    @Jhunt9 - Could you add print "%s\\%s.tif" %(myDir, layer.name() ) inside your loop to see exactly what the paths look like? – Joseph Jun 9 '17 at 12:55
  • 2
    Is it possible that an escape sequence is ruining your path? Try: myDir = r'C:\temp' --> \t is an escape sequence – AndreasK Jun 9 '17 at 12:59
  • 1
    Yes! The escape charater got you! --> python-reference.readthedocs.io/en/latest/docs/str/escapes.html – AndreasK Jun 9 '17 at 13:01
1
myDir = r'C:\temp'
layers = layers = iface.mapCanvas().layers()
pipe = QgsRasterPipe()
for layer in layers:
    extent = layer.extent()
   width, height = layer.width(), layer.height()
   renderer = layer.renderer()
   provider=layer.dataProvider()
   crs = layer.crs().toWkt() 
   pipe.set(provider.clone())
   pipe.set(renderer.clone())
   file_writer = QgsRasterFileWriter("%s\\%s.tif" %(myDir, layer.name() ))
   file_writer.writeRaster(pipe,
                       width,
                       height,
                       extent,
                       layer.crs())
   print "%s\\%s.tif" %(myDir, layer.name() )

This is the Code that worked! Thank you @LaughU, @AndreasK, & @Joseph

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.