Skip to content

Instantly share code, notes, and snippets.

@ljvmiranda921
Last active July 27, 2021 22:52
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ljvmiranda921/47c82acb6d42a3ccb9c6828c786043a9 to your computer and use it in GitHub Desktop.
Save ljvmiranda921/47c82acb6d42a3ccb9c6828c786043a9 to your computer and use it in GitHub Desktop.
QGIS method to export RAW image into rendered image
def export_as_rendered_image(layer, outfile):
"""Export a QGIS Layer as the rendered image
Usage
-----
Use this while working inside QGIS. As of now, I'm not sure
how to run this outside of QGIS. In addition, files are saved
in your home directory
..code-block:: python
# Get active layer, assuming it's loaded in QGIS already
layer = iface.activeLayer()
outfile = 'rendered_image' # No file extension!
export_as_rendered_image(layer, outfile)
# To run on multiple layers, first get a list of layers, and
# a list of strings for output filenames. Ensure that
# len(layers) == len(outfiles)
layers = iface.mapCanvas().layers()
outfiles = [] # list of output files
for layer, outfile in zip(layers, outfiles):
export_as_rendered_image(layer, outfile)
Parameters
----------
layer : list of qcis._core.QgsRasterLayer
outfile : list of str
"""
extent = layer.extent()
width, height = layer.width(), layer.height()
renderer = layer.renderer()
provider=layer.dataProvider()
crs = layer.crs().toWkt()
pipe = QgsRasterPipe()
pipe.set(provider.clone())
pipe.set(renderer.clone())
filename = '{}.tif'.format(outfile)
file_writer = QgsRasterFileWriter(filename)
file_writer.writeRaster(pipe,
width,
height,
extent,
layer.crs())
print('Exported {}'.format(filename))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment