Search code examples
pythongdalqgis

Creating in-memory QgsRasterlayer from the rasterization of a QgsVectorLayer with PyQGIS?


I am currently building a QGIS plugin and I need to rasterize a vector layer where the output will be stored in memory.

To do so, I tried this (which come from the answer from this link) :

temp = processing.run("gdal:rasterize",
                           {"INPUT": input_shapefile,
                            "FIELD": "OBJECTID",
                            "UNITS": 1,
                            "WIDTH": resolution,
                            "HEIGHT": resolution,
                            "EXTENT": "%f,%f,%f,%f" % (xmin, xmax, ymin, ymax),
                            "NODATA": -99,
                            "OUTPUT": None})

The problem is that it does not work : None is not recognized as a valid output. I also tried "OUTPUT" : "memory" but it is not working neither... So I wonder if this answer that I found in the link above is correct ?

Note : QGIS version : 3.4.7 with Python 3.7


Solution

  • I found an aswer to my question using "tempfile.TemporaryDirectory()" in the following way :

    tf = tempfile.TemporaryDirectory()
    tfolder = tf.name + "\\rasterisation.tif"
    temp = processing.run("gdal:rasterize",
                           {"INPUT": input_shapefile,
                            "FIELD": "OBJECTID",
                            "UNITS": 1,
                            "WIDTH": resolution,
                            "HEIGHT": resolution,
                            "EXTENT": "%f,%f,%f,%f" % (xmin, xmax, ymin, ymax),
                            "NODATA": -99,
                            "OUTPUT": tfolder})
     rlayer = self.iface.addRasterLayer(tfolder, "Rasterisation")
    

    See this link for more information on this module.