3

I would like to create a singleBand raster (grayScale) using the method qgis.core.QgsRasterFileWriter.writeRaster

According to the documentation:

writeRaster(self, 
    pipe: QgsRasterPipe, 
    nCols: int,
    nRows: int,  
    outputExtent: QgsRectangle, 
    crs: QgsCoordinateReferenceSystem, 
    feedback: QgsRasterBlockFeedback = None
) → QgsRasterFileWriter.WriterError

You may be agree that this documentation is very unclear on how to use it... I success to create vectorLayer from QgsVectorFileWriter.writeAsVectorFormat.

But there is too few examples on internet using QgsRasterFileWriter...

Here is the example script I have for the moment:

import os
import numpy
from qgis.core import (
    QgsMapLayer,
    QgsRasterFileWriter,
    QgsCoordinateReferenceSystem,
    QgsRectangle,
    Qgis,
)


def write_to_geotiff(data: list, filename: str, epsg: str, layer: str=None) -> None:
    
    x_data = data[0]
    y_data = data[1]
    z_data = data[2]
    
    nx, ny = len(x_data), len(y_data)

   ##########
   # CODE HERE
   ##########

I saw this solution to create a raster but I don t want to use GDAL because off env issues related to GDAL...

1 Answer 1

2

I get it using the method QgsRasterFileWriter.createOneBandRaster creating a provider. You can get the bloc of the provider of type QgsRasterBlock and use the method setValue to associate values.

    writer = QgsRasterFileWriter(filename)
    provider = QgsRasterFileWriter.createOneBandRaster(
        writer,
        dataType=Qgis.Float32,
        width=nx,
        height=ny,
        extent=QgsRectangle(
            min(x_data),
            min(y_data),
            max(x_data),
            max(y_data)
        ),
        crs = QgsCoordinateReferenceSystem(f"epsg:{epsg}"),
    )
    provider.setNoDataValue(1, -1)
    provider.setEditable(True)
    
    block = provider.block(
        bandNo=1,
        boundingBox=provider.extent(),
        width=provider.xSize(),
        height=provider.ySize()
    )
    
    for ix in range(nx):
        for iy in range(ny):
            value = z_data[ix][iy]
            if value == numpy.nan:
                continue
            block.setValue(iy, ix, value)
    
    provider.writeBlock(
        block=block, 
        band=1,
        xOffset=0,
        yOffset=0
    )
    provider.setEditable(False)
    

This will create a tiffile:

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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