I could get the same TypeError
:
File "C:\OSGeo4W\apps\Python312\Lib\code.py", line 90, in runcode
exec(code, self.locals)
File "<input>", line 1, in <module>
File "<string>", line 8, in <module>
TypeError: QgsRasterFileWriter.writeRaster(): arguments did not match any overloaded call:
overload 1: argument 1 has unexpected type 'int'
overload 2: argument 1 has unexpected type 'int'
when I proceeded with this script:
from qgis.utils import iface
from qgis.core import QgsRasterFileWriter
layer = iface.activeLayer()
provider = layer.dataProvider()
out_file = provider.dataSourceUri().replace('.tif', '.img')
file_writer = QgsRasterFileWriter(out_file)
result = file_writer.writeRaster(provider.xSize(), provider.xSize(), provider.extent(), provider.crs())
As was mentioned in @user30184's comment it is vital to include the pipe
-parameter of the QgsRasterPipe
class type:
Contains a pipeline of raster interfaces for sequential raster processing.
There are also several suggestions regarding your code:
check firstly details about the
writeRaster()
-method withhelp(QgsRasterFileWriter.writeRaster)
:Help on built-in function writeRaster: writeRaster(...) writeRaster(self, pipe: Optional[QgsRasterPipe], nCols: int, nRows: int, outputExtent: QgsRectangle, crs: QgsCoordinateReferenceSystem, feedback: Optional[QgsRasterBlockFeedback] = None) -> Qgis.RasterFileWriterResult Write raster file :param pipe: raster pipe :param nCols: number of output columns :param nRows: number of output rows (or -1 to automatically calculate row number to have square pixels) :param outputExtent: extent to output :param crs: crs to reproject to :param feedback: optional feedback object for progress reports .. deprecated:: QGIS 3.8 use version with transformContext instead
treat file export results properly using the
Qgis.RasterFileWriterResult
make use of the
QgsRasterBlockFeedback
class and itserrors()
-method to get more details about errors while retrieving the raster blockapply the Python Try Except blocks to handle errors and exceptions
check if your input
QgsRasterLayer
is solid with theisValid()
-methodimports can be useful to make your code reusable in the future in standalone applications
delete the writer object with
del
statement
In the end, your code may look as follows:
from qgis.utils import iface
from qgis.core import Qgis, QgsRasterPipe, QgsRasterFileWriter, QgsRasterBlockFeedback
layer = iface.activeLayer()
if layer.isValid():
provider = layer.dataProvider()
pipe = QgsRasterPipe()
pipe.set(provider.clone())
out_file = provider.dataSourceUri().replace('.tif', '.img')
file_writer = QgsRasterFileWriter(out_file)
try:
feedback = QgsRasterBlockFeedback()
result = file_writer.writeRaster(pipe, provider.xSize(), provider.xSize(), provider.extent(), provider.crs(), feedback)
if result != Qgis.RasterFileWriterResult.Success:
print(feedback.errors())
except Exception as e:
print(e)
del file_writer
References: