Class: QgsRasterLayer

class qgis.core.QgsRasterLayer

Bases: QgsMapLayer

Constructor. Provider is not set.

QgsRasterLayer(uri: str, baseName: str = ‘’, providerKey: str = ‘’, options: QgsRasterLayer.LayerOptions = QgsRasterLayer.LayerOptions()) This is the constructor for the RasterLayer class.

The main tasks carried out by the constructor are:

-Load the rasters default style (.qml) file if it exists

-Populate the RasterStatsVector with initial values for each band.

-Calculate the layer extents

-Determine whether the layer is gray, paletted or multiband.

-Assign sensible defaults for the red, green, blue and gray bands.

This class provides qgis with the ability to render raster datasets onto the mapcanvas.

The qgsrasterlayer class makes use of gdal for data io, and thus supports any gdal supported format. The constructor attempts to infer what type of file (LayerType) is being opened - not in terms of the file format (tif, ascii grid etc.) but rather in terms of whether the image is a GRAYSCALE, PaletteD or Multiband,

Within the three allowable raster layer types, there are 8 permutations of how a layer can actually be rendered. These are defined in the DrawingStyle enum and consist of:

SingleBandGray -> a GRAYSCALE layer drawn as a range of gray colors (0-255) SingleBandPseudoColor -> a GRAYSCALE layer drawn using a pseudocolor algorithm PalettedSingleBandGray -> a PaletteD layer drawn in gray scale (using only one of the color components) PalettedSingleBandPseudoColor -> a PaletteD layer having only one of its color components rendered as pseudo color PalettedMultiBandColor -> a PaletteD image where the bands contains 24bit color info and 8 bits is pulled out per color MultiBandSingleBandGray -> a layer containing 2 or more bands, but using only one band to produce a grayscale image MultiBandSingleBandPseudoColor -> a layer containing 2 or more bands, but using only one band to produce a pseudocolor image MultiBandColor -> a layer containing 2 or more bands, mapped to the three RGBcolors. In the case of a multiband with only two bands, one band will have to be mapped to more than one color

Each of the above mentioned drawing styles is implemented in its own draw* function. Some of the drawing styles listed above require statistics about the layer such as the min / max / mean / stddev etc. statistics for a band can be gathered using the bandStatistics function. Note that statistics gathering is a slow process and every effort should be made to call this function as few times as possible. For this reason, qgsraster has a vector class member to store stats for each band. The constructor initializes this vector on startup, but only populates the band name and number fields.

Note that where bands are of gdal ‘undefined’ type, their values may exceed the renderable range of 0-255. Because of this a linear scaling histogram enhanceContrast is applied to undefined layers to normalise the data into the 0-255 range.

A qgsrasterlayer band can be referred to either by name or by number (base=1). It should be noted that band names as stored in datafiles may not be unique, and so the rasterlayer class appends the band number in brackets behind each band name.

Sample usage of the QgsRasterLayer class:

In order to automate redrawing of a raster layer, you should like it to a map canvas like this :

Once a layer has been created you can find out what type of layer it is (GrayOrUndefined, Palette or Multiband):

Raster layers can also have an arbitrary level of transparency defined, and have their color palettes inverted using the setTransparency and setInvertHistogram methods.

Pseudocolor images can have their output adjusted to a given number of standard deviations using the setStandardDeviations method.

The final area of functionality you may be interested in is band mapping. Band mapping allows you to choose arbitrary band -> color mappings and is applicable only to Palette and Multiband rasters, There are four mappings that can be made: red, green, blue and gray. Mappings are non-exclusive. That is a given band can be assigned to no, some or all color mappings. The constructor sets sensible defaults for band mappings but these can be overridden at run time using the setRedBandName, setGreenBandName, setBlueBandName and setGrayBandName methods.

Methods

appendError

bandCount

Returns the number of bands in this layer.

bandName

Returns the name of a band given its number.

brightnessFilter

rtype

QgsBrightnessContrastFilter

childEvent

clone

Returns a new instance equivalent to this one.

connectNotify

constDataProvider

rtype

QgsRasterDataProvider

createMapRenderer

param rendererContext

customEvent

dataProvider

rtype

QgsRasterDataProvider

decodedSource

param source

disconnectNotify

draw

This is an overloaded version of the draw() function that is called by both draw() and thumbnailAsPixmap

encodedSource

param source

hasDependencyCycle

height

Returns the height of the (unclipped) raster.

htmlMetadata

rtype

str

hueSaturationFilter

rtype

QgsHueSaturationFilter

isSignalConnected

isSpatial

rtype

bool

isValidRasterFileName

This helper checks to see whether the file name appears to be a valid raster file name.

lastModified

Returns time stamp for given file name

legendSymbologyItems

Returns a list with classification items (Text and color)

paletteAsPixmap

Returns a 100x100 pixmap of the color palette.

pipe

Returns the raster pipe.

previewAsImage

Draws a preview of the rasterlayer into a QImage

providerType

[ data provider interface ] Which provider is being used for this Raster Layer?

rasterType

Returns the raster layer type (which is a read only property).

rasterUnitsPerPixelX

Returns the number of raster units per each raster pixel in X axis.

rasterUnitsPerPixelY

Returns the number of raster units per each raster pixel in Y axis.

readCommonStyle

readCustomProperties

readStyle

param node

readStyleManager

readSymbology

param node

readXml

param layer_node

receivers

reload

renderer

rtype

QgsRasterRenderer

resampleFilter

Sets raster resample filter.

sender

senderSignalIndex

setContrastEnhancement

Set contrast enhancement algorithm

setDataProvider

Set the data provider.

setDefaultContrastEnhancement

Sets the default contrast enhancement

setError

setExtent

setLayerOrder

param layers

setRenderer

Sets raster renderer.

setSubLayerVisibility

param name

setValid

showStatusMessage

param message

subLayers

rtype

List[str]

timerEvent

timestamp

rtype

QDateTime

width

Returns the width of the (unclipped) raster.

writeCommonStyle

writeCustomProperties

writeSld

Writes the symbology of the layer into the document provided in SLD 1.0.0 format

writeStyle

param node

writeStyleManager

writeSymbology

param a0

writeXml

param layer_node

Attributes

ColorLayer

ColorRampShader

FreakOutShader

GrayOrUndefined

MULTIPLE_BAND_MULTI_BYTE_ENHANCEMENT_ALGORITHM

MULTIPLE_BAND_MULTI_BYTE_MIN_MAX_LIMITS

MULTIPLE_BAND_SINGLE_BYTE_ENHANCEMENT_ALGORITHM

MULTIPLE_BAND_SINGLE_BYTE_MIN_MAX_LIMITS

Multiband

Palette

PseudoColorShader

SAMPLE_SIZE

SINGLE_BAND_ENHANCEMENT_ALGORITHM

SINGLE_BAND_MIN_MAX_LIMITS

UndefinedShader

UserDefinedShader

ColorLayer = 3
ColorRampShader = 3
class ColorShadingAlgorithm

Bases: int

FreakOutShader = 2
GrayOrUndefined = 0
class LayerOptions(loadDefaultStyle: bool = True)

Bases: sip.wrapper

Constructor for LayerOptions.

QgsRasterLayer.LayerOptions(QgsRasterLayer.LayerOptions)

Parameters

loadDefaultStyle (bool = True) –

loadDefaultStyle
class LayerType

Bases: int

MULTIPLE_BAND_MULTI_BYTE_ENHANCEMENT_ALGORITHM = 1
MULTIPLE_BAND_MULTI_BYTE_MIN_MAX_LIMITS = 3
MULTIPLE_BAND_SINGLE_BYTE_ENHANCEMENT_ALGORITHM = 0
MULTIPLE_BAND_SINGLE_BYTE_MIN_MAX_LIMITS = 1
Multiband = 2
Palette = 1
PseudoColorShader = 1
SAMPLE_SIZE = 250000.0
SINGLE_BAND_ENHANCEMENT_ALGORITHM = 1
SINGLE_BAND_MIN_MAX_LIMITS = 1
UndefinedShader = 0
UserDefinedShader = 4
appendError()
bandCount(self) → int

Returns the number of bands in this layer.

Return type

int

bandName(self, bandNoInt: int) → str

Returns the name of a band given its number.

Parameters

bandNoInt (int) –

Return type

str

brightnessFilter(self) → QgsBrightnessContrastFilter
Return type

QgsBrightnessContrastFilter

childEvent()
clone(self) → QgsRasterLayer

Returns a new instance equivalent to this one. A new provider is created for the same data source and renderer is cloned too.

Return type

QgsRasterLayer

Returns

a new layer instance

New in version 3.0.

connectNotify()
constDataProvider(self) → QgsRasterDataProvider
Return type

QgsRasterDataProvider

createMapRenderer(self, rendererContext: QgsRenderContext) → QgsMapLayerRenderer
Parameters

rendererContext (QgsRenderContext) –

Return type

QgsMapLayerRenderer

customEvent()
dataProvider(self) → QgsRasterDataProvider
Return type

QgsRasterDataProvider

decodedSource(self, source: str, provider: str, context: QgsReadWriteContext) → str
Parameters
Return type

str

disconnectNotify()
draw(self, theQPainter: QPainter, myRasterViewPort: QgsRasterViewPort, qgsMapToPixel: QgsMapToPixel = None)

This is an overloaded version of the draw() function that is called by both draw() and thumbnailAsPixmap

Parameters
encodedSource(self, source: str, context: QgsReadWriteContext) → str
Parameters
Return type

str

hasDependencyCycle()
height(self) → int

Returns the height of the (unclipped) raster.

See also

width()

Return type

int

htmlMetadata(self) → str
Return type

str

hueSaturationFilter(self) → QgsHueSaturationFilter
Return type

QgsHueSaturationFilter

isSignalConnected()
isSpatial(self) → bool
Return type

bool

isValidRasterFileName(fileNameQString: str, retError: str) → bool

This helper checks to see whether the file name appears to be a valid raster file name. If the file name looks like it could be valid, but some sort of error occurs in processing the file, the error is returned in retError.

isValidRasterFileName(fileNameQString: str) -> bool

Parameters
  • fileNameQString (str) –

  • retError (str) –

Return type

bool

lastModified(name: str) → QDateTime

Returns time stamp for given file name

Parameters

name (str) –

Return type

QDateTime

legendSymbologyItems(self) → object

Returns a list with classification items (Text and color)

Return type

object

paletteAsPixmap(self, bandNumber: int = 1) → QPixmap

Returns a 100x100 pixmap of the color palette. If the layer has no palette a white pixmap will be returned

Parameters

bandNumber (int = 1) – the number of the band to use for generating a pixmap of the associated palette

Return type

QPixmap

pipe(self) → QgsRasterPipe

Returns the raster pipe.

Return type

QgsRasterPipe

previewAsImage(self, size: QSize, bgColor: Union[QColor, Qt.GlobalColor] = Qt.white, format: QImage.Format = QImage.Format_ARGB32_Premultiplied) → QImage

Draws a preview of the rasterlayer into a QImage

New in version 2.4.

Parameters
  • size (QSize) –

  • bgColor (Union[QColor) –

  • format (QImage.Format = QImage.Format_ARGB32_Premultiplied) –

Return type

QImage

providerType(self) → str

[ data provider interface ] Which provider is being used for this Raster Layer?

Return type

str

rasterType(self) → QgsRasterLayer.LayerType

Returns the raster layer type (which is a read only property).

Return type

QgsRasterLayer.LayerType

rasterUnitsPerPixelX(self) → float

Returns the number of raster units per each raster pixel in X axis.

In a world file, this is normally the first row (without the sign). (E.g. the value reported by the GDAL geotransform[1]).

Return type

float

rasterUnitsPerPixelY(self) → float

Returns the number of raster units per each raster pixel in Y axis.

In a world file, this is normally the first row (without the sign).

Return type

float

readCommonStyle()
readCustomProperties()
readStyle(self, node: QDomNode, errorMessage: str, context: QgsReadWriteContext, categories: Union[QgsMapLayer.StyleCategories, QgsMapLayer.StyleCategory] = QgsMapLayer.AllStyleCategories) → bool
Parameters
Return type

bool

readStyleManager()
readSymbology(self, node: QDomNode, errorMessage: str, context: QgsReadWriteContext, categories: Union[QgsMapLayer.StyleCategories, QgsMapLayer.StyleCategory] = QgsMapLayer.AllStyleCategories) → bool
Parameters
Return type

bool

readXml(self, layer_node: QDomNode, context: QgsReadWriteContext) → bool
Parameters
Return type

bool

receivers()
reload(self)
renderer(self) → QgsRasterRenderer
Return type

QgsRasterRenderer

resampleFilter(self) → QgsRasterResampleFilter

Sets raster resample filter. Takes ownership of the resample filter object

Return type

QgsRasterResampleFilter

sender()
senderSignalIndex()
setContrastEnhancement(self, algorithm: QgsContrastEnhancement.ContrastEnhancementAlgorithm, limits: QgsRasterMinMaxOrigin.Limits = QgsRasterMinMaxOrigin.MinMax, extent: QgsRectangle = QgsRectangle(), sampleSize: int = QgsRasterLayer.SAMPLE_SIZE, generateLookupTableFlag: bool = True)

Set contrast enhancement algorithm

Parameters
  • algorithm (QgsContrastEnhancement.ContrastEnhancementAlgorithm) – Contrast enhancement algorithm

  • limits (QgsRasterMinMaxOrigin.Limits = QgsRasterMinMaxOrigin.MinMax) – Limits

  • extent (QgsRectangle = QgsRectangle()) – Extent used to calculate limits, if empty, use full layer extent

  • sampleSize (int = QgsRasterLayer.SAMPLE_SIZE) – Size of data sample to calculate limits, if 0, use full resolution

  • generateLookupTableFlag (bool = True) – Generate lookup table. *

setDataProvider(self, provider: str)

Set the data provider.

Deprecated since version Use: the version with ProviderOptions instead.

setDataProvider(self, provider: str, options: QgsDataProvider.ProviderOptions) Set the data provider.

Parameters
  • provider (str) – provider key string, must match a valid QgsRasterDataProvider key. E.g. “gdal”, “wms”, etc.

  • options – provider options

New in version 3.2.

setDefaultContrastEnhancement(self)

Sets the default contrast enhancement

setError()
setExtent()
setLayerOrder(self, layers: Iterable[str])
Parameters

layers (Iterable[str]) –

setRenderer(self, renderer: QgsRasterRenderer)

Sets raster renderer. Takes ownership of the renderer object

Parameters

renderer (QgsRasterRenderer) –

setSubLayerVisibility(self, name: str, vis: bool)
Parameters
  • name (str) –

  • vis (bool) –

setValid()
showStatusMessage(self, message: str)
Parameters

message (str) –

subLayers(self) → List[str]
Return type

List[str]

timerEvent()
timestamp(self) → QDateTime
Return type

QDateTime

width(self) → int

Returns the width of the (unclipped) raster.

See also

height()

Return type

int

writeCommonStyle()
writeCustomProperties()
writeSld(self, node: QDomNode, doc: QDomDocument, errorMessage: str, props: Dict[str, str] = {}) → bool

Writes the symbology of the layer into the document provided in SLD 1.0.0 format

Parameters
  • node (QDomNode) – the node that will have the style element added to it.

  • doc (QDomDocument) – the document that will have the QDomNode added.

  • errorMessage (str) – reference to string that will be updated with any error messages

  • props (Dict[str) – a open ended set of properties that can drive/inform the SLD encoding

Return type

bool

Returns

true in case of success

New in version 3.4.5.

writeStyle(self, node: QDomNode, doc: QDomDocument, errorMessage: str, context: QgsReadWriteContext, categories: Union[QgsMapLayer.StyleCategories, QgsMapLayer.StyleCategory] = QgsMapLayer.AllStyleCategories) → bool
Parameters
Return type

bool

writeStyleManager()
writeSymbology(self, a0: QDomNode, doc: QDomDocument, errorMessage: str, context: QgsReadWriteContext, categories: Union[QgsMapLayer.StyleCategories, QgsMapLayer.StyleCategory] = QgsMapLayer.AllStyleCategories) → bool
Parameters
Return type

bool

writeXml(self, layer_node: QDomNode, doc: QDomDocument, context: QgsReadWriteContext) → bool
Parameters
Return type

bool