QgsRasterLayer class
This class provides qgis with the ability to render raster datasets onto the mapcanvas.
Contents
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:
QString myFileNameQString = "/path/to/file"; QString myBaseNameQString = "my layer"; QgsRasterLayer *myRasterLayer = new QgsRasterLayer(myFileNameQString, myBaseNameQString);
In order to automate redrawing of a raster layer, you should like it to a map canvas like this :
QObject::connect( myRasterLayer, SIGNAL(repaintRequested()), mapCanvas, SLOT(refresh()) );
Once a layer has been created you can find out what type of layer it is (GrayOrUndefined, Palette or Multiband):
if (rasterLayer->rasterType()==QgsRasterLayer::Multiband) { //do something } else if (rasterLayer->rasterType()==QgsRasterLayer::Palette) { //do something } else // QgsRasterLayer::GrayOrUndefined { //do something. }
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.
Base classes
- class QgsMapLayer
- Base class for all map layer types.
Public types
- struct LayerOptions
- Setting options for loading raster layers.
- enum ColorShadingAlgorithm { UndefinedShader, PseudoColorShader, FreakOutShader, ColorRampShader, UserDefinedShader }
- This enumerator describes the types of shading that can be used.
- enum LayerType { GrayOrUndefined, Palette, Multiband, ColorLayer }
- This enumerator describes the type of raster layer.
Public static variables
-
static const QgsContrastEnhancement::
ContrastEnhancementAlgorithm MULTIPLE_BAND_MULTI_BYTE_ENHANCEMENT_ALGORITHM - Default enhancement algorithm for multiple band raster of type different from Byte.
-
static const QgsRasterMinMaxOrigin::
Limits MULTIPLE_BAND_MULTI_BYTE_MIN_MAX_LIMITS - Default enhancement limits for multiple band raster of type different from Byte.
-
static const QgsContrastEnhancement::
ContrastEnhancementAlgorithm MULTIPLE_BAND_SINGLE_BYTE_ENHANCEMENT_ALGORITHM - Default enhancement algorithm for multiple band raster of type Byte.
-
static const QgsRasterMinMaxOrigin::
Limits MULTIPLE_BAND_SINGLE_BYTE_MIN_MAX_LIMITS - Default enhancement limits for multiple band raster of type Byte.
- static const double SAMPLE_SIZE
- Default sample size (number of pixels) for estimated statistics/histogram calculation.
-
static const QgsContrastEnhancement::
ContrastEnhancementAlgorithm SINGLE_BAND_ENHANCEMENT_ALGORITHM - Default enhancement algorithm for single band raster.
-
static const QgsRasterMinMaxOrigin::
Limits SINGLE_BAND_MIN_MAX_LIMITS - Default enhancement limits for single band raster.
Public static functions
- static auto isValidRasterFileName(const QString& fileNameQString, QString& retError) -> bool
- This helper checks to see whether the file name appears to be a valid raster file name.
- static auto lastModified(const QString& name) -> QDateTime
- Returns time stamp for given file name.
Constructors, destructors, conversion operators
- QgsRasterLayer()
- Constructor. Provider is not set.
-
QgsRasterLayer(const QString& uri,
const QString& baseName = QString(),
const QString& providerType = "gdal",
const QgsRasterLayer::
LayerOptions& options = QgsRasterLayer:: LayerOptions()) explicit - This is the constructor for the RasterLayer class.
Public functions
- auto bandCount() const -> int
- Returns the number of bands in this layer.
- auto bandName(int bandNoInt) const -> QString
- Returns the name of a band given its number.
- auto clone() const -> QgsRasterLayer* override
- Returns a new instance equivalent to this one.
- auto createMapRenderer(QgsRenderContext& rendererContext) -> QgsMapLayerRenderer* override
- Returns new instance of QgsMapLayerRenderer that will be used for rendering of given context.
- auto dataProvider() -> QgsRasterDataProvider* override
- Returns the layer's data provider, it may be null.
- auto dataProvider() const -> const QgsRasterDataProvider* override
- Returns the layer's data provider in a const-correct manner, it may be null.
-
auto defaultContrastEnhancementSettings(QgsContrastEnhancement::
ContrastEnhancementAlgorithm& myAlgorithm, QgsRasterMinMaxOrigin:: Limits& myLimits) const -> bool - Returns default contrast enhancement settings for that type of raster.
- void draw(QPainter* theQPainter, QgsRasterViewPort* myRasterViewPort, const QgsMapToPixel* qgsMapToPixel = nullptr)
- This is an overloaded version of the draw() function that is called by both draw() and thumbnailAsPixmap.
- auto height() const -> int
- Returns the height of the (unclipped) raster.
- auto htmlMetadata() const -> QString override
- Obtain a formatted HTML string containing assorted metadata for this layer.
- auto isSpatial() const -> bool override
- Returns true if the layer is considered a spatial layer, ie it has some form of geometry associated with it.
- auto legendSymbologyItems() const -> QgsLegendColorList
- Returns a list with classification items (Text and color)
- auto paletteAsPixmap(int bandNumber = 1) -> QPixmap
- Returns a 100x100 pixmap of the color palette.
- auto pipe() -> QgsRasterPipe*
- Returns the raster pipe.
- auto previewAsImage(QSize size, const QColor& bgColor = Qt::white, QImage::Format format = QImage::Format_ARGB32_Premultiplied) -> QImage
- Draws a preview of the rasterlayer into a QImage.
- auto providerType() const -> QString
- [ data provider interface ] Which provider is being used for this Raster Layer?
- auto rasterType() -> LayerType
- Returns the raster layer type (which is a read only property).
- auto rasterUnitsPerPixelX() const -> double
- Returns the number of raster units per each raster pixel in X axis.
- auto rasterUnitsPerPixelY() const -> double
- Returns the number of raster units per each raster pixel in Y axis.
- void refreshContrastEnhancement(const QgsRectangle& extent)
- Refresh contrast enhancement with new extent.
- void refreshRendererIfNeeded(QgsRasterRenderer* rasterRenderer, const QgsRectangle& extent)
- Refresh renderer with new extent, if needed.
- void reload() override
- Synchronises with changes in the datasource.
- auto resampleFilter() const -> QgsRasterResampleFilter*
- Sets raster resample filter. Takes ownership of the resample filter object.
-
void setContrastEnhancement(QgsContrastEnhancement::
ContrastEnhancementAlgorithm algorithm, QgsRasterMinMaxOrigin:: Limits limits = QgsRasterMinMaxOrigin:: MinMax, const QgsRectangle& extent = QgsRectangle(), int sampleSize = QgsRasterLayer:: SAMPLE_SIZE, bool generateLookupTableFlag = true) - Set contrast enhancement algorithm.
- auto setDataProvider(const QString& provider) -> Q_DECL_DEPRECATED void deprecated
- Set the data provider.
-
void setDataProvider(const QString& provider,
const QgsDataProvider::
ProviderOptions& options) - Set the data provider.
-
void setDataSource(const QString& dataSource,
const QString& baseName,
const QString& provider,
const QgsDataProvider::
ProviderOptions& options, bool loadDefaultStyleFlag = false) override - Updates the data source of the layer.
- void setDefaultContrastEnhancement()
- Sets the default contrast enhancement.
- void setLayerOrder(const QStringList& layers) override
- Reorders the previously selected sublayers of this layer from bottom to top.
- void setRenderer(QgsRasterRenderer* renderer)
- Sets raster renderer. Takes ownership of the renderer object.
- void setSubLayerVisibility(const QString& name, bool visible) override
- Set the visibility of the given sublayer name.
- auto subLayers() const -> QStringList override
- Returns the sublayers of this layer.
- auto timestamp() const -> QDateTime override
- Time stamp of data source in the moment when data/metadata were loaded by provider.
- auto width() const -> int
- Returns the width of the (unclipped) raster.
Protected functions
- auto decodedSource(const QString& source, const QString& dataProvider, const QgsReadWriteContext& context) const -> QString override
- Called by readLayerXML(), used by derived classes to decode provider's specific data source from project files.
- auto encodedSource(const QString& source, const QgsReadWriteContext& context) const -> QString override
- Called by writeLayerXML(), used by derived classes to encode provider's specific data source to project files.
- auto readXml(const QDomNode& layer_node, QgsReadWriteContext& context) -> bool override
- Called by readLayerXML(), used by children to read state specific to them from project files.
- auto writeXml(QDomNode& layer_node, QDomDocument& document, const QgsReadWriteContext& context) const -> bool override
- Called by writeLayerXML(), used by children to write state specific to them to project files.
Function documentation
static bool QgsRasterLayer:: isValidRasterFileName(const QString& fileNameQString,
QString& retError)
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.
QgsRasterLayer:: QgsRasterLayer(const QString& uri,
const QString& baseName = QString(),
const QString& providerType = "gdal",
const QgsRasterLayer:: LayerOptions& options = QgsRasterLayer:: LayerOptions()) explicit
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.
QgsRasterLayer* QgsRasterLayer:: clone() const override
Returns a new instance equivalent to this one.
| Returns | a new layer instance |
|---|
A new provider is created for the same data source and renderer is cloned too.
QgsMapLayerRenderer* QgsRasterLayer:: createMapRenderer(QgsRenderContext& rendererContext) override
Returns new instance of QgsMapLayerRenderer that will be used for rendering of given context.
const QgsRasterDataProvider* QgsRasterLayer:: dataProvider() const override
Returns the layer's data provider in a const-correct manner, it may be null.
bool QgsRasterLayer:: defaultContrastEnhancementSettings(QgsContrastEnhancement:: ContrastEnhancementAlgorithm& myAlgorithm,
QgsRasterMinMaxOrigin:: Limits& myLimits) const
Returns default contrast enhancement settings for that type of raster.
int QgsRasterLayer:: height() const
Returns the height of the (unclipped) raster.
QString QgsRasterLayer:: htmlMetadata() const override
Obtain a formatted HTML string containing assorted metadata for this layer.
bool QgsRasterLayer:: isSpatial() const override
Returns true if the layer is considered a spatial layer, ie it has some form of geometry associated with it.
QPixmap QgsRasterLayer:: paletteAsPixmap(int bandNumber = 1)
Returns a 100x100 pixmap of the color palette.
| Parameters | |
|---|---|
| bandNumber | the number of the band to use for generating a pixmap of the associated palette |
If the layer has no palette a white pixmap will be returned
QImage QgsRasterLayer:: previewAsImage(QSize size,
const QColor& bgColor = Qt::white,
QImage::Format format = QImage::Format_ARGB32_Premultiplied)
Draws a preview of the rasterlayer into a QImage.
double QgsRasterLayer:: rasterUnitsPerPixelX() const
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]).
double QgsRasterLayer:: rasterUnitsPerPixelY() const
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).
void QgsRasterLayer:: refreshContrastEnhancement(const QgsRectangle& extent)
Refresh contrast enhancement with new extent.
void QgsRasterLayer:: refreshRendererIfNeeded(QgsRasterRenderer* rasterRenderer,
const QgsRectangle& extent)
Refresh renderer with new extent, if needed.
void QgsRasterLayer:: setContrastEnhancement(QgsContrastEnhancement:: ContrastEnhancementAlgorithm algorithm,
QgsRasterMinMaxOrigin:: Limits limits = QgsRasterMinMaxOrigin:: MinMax,
const QgsRectangle& extent = QgsRectangle(),
int sampleSize = QgsRasterLayer:: SAMPLE_SIZE,
bool generateLookupTableFlag = true)
Set contrast enhancement algorithm.
| Parameters | |
|---|---|
| algorithm | Contrast enhancement algorithm |
| limits | Limits |
| extent | Extent used to calculate limits, if empty, use full layer extent |
| sampleSize | Size of data sample to calculate limits, if 0, use full resolution |
| generateLookupTableFlag | Generate lookup table. |
Q_DECL_DEPRECATED void QgsRasterLayer:: setDataProvider(const QString& provider)
Set the data provider.
void QgsRasterLayer:: setDataProvider(const QString& provider,
const QgsDataProvider:: ProviderOptions& options)
Set the data provider.
| Parameters | |
|---|---|
| provider | provider key string, must match a valid QgsRasterDataProvider key. E.g. "gdal", "wms", etc. |
| options | provider options |
void QgsRasterLayer:: setDataSource(const QString& dataSource,
const QString& baseName,
const QString& provider,
const QgsDataProvider:: ProviderOptions& options,
bool loadDefaultStyleFlag = false) override
Updates the data source of the layer.
| Parameters | |
|---|---|
| dataSource | new layer data source |
| baseName | base name of the layer |
| provider | provider string |
| options | provider options |
| loadDefaultStyleFlag | set to true to reset the layer's style to the default for the data source |
The layer's renderer and legend will be preserved only if the geometry type of the new data source matches the current geometry type of the layer.
void QgsRasterLayer:: setLayerOrder(const QStringList& layers) override
Reorders the previously selected sublayers of this layer from bottom to top.
(Useful for providers that manage their own layers, such as WMS).
void QgsRasterLayer:: setSubLayerVisibility(const QString& name,
bool visible) override
Set the visibility of the given sublayer name.
| Parameters | |
|---|---|
| name | sublayer name |
| visible | sublayer visibility |
QStringList QgsRasterLayer:: subLayers() const override
Returns the sublayers of this layer.
(Useful for providers that manage their own layers, such as WMS).
int QgsRasterLayer:: width() const
Returns the width of the (unclipped) raster.
QString QgsRasterLayer:: decodedSource(const QString& source,
const QString& dataProvider,
const QgsReadWriteContext& context) const override protected
Called by readLayerXML(), used by derived classes to decode provider's specific data source from project files.
| Parameters | |
|---|---|
| source | data source to decode, typically read from layer's DOM element "datasource" |
| dataProvider | string identification of data provider (e.g. "ogr"), typically read from layer's DOM element |
| context | reading context (e.g. for conversion between relative and absolute paths) |
| Returns | decoded source, typically to be used as the layer's datasource |
Typically resolving absolute or relative paths, usernames and passwords or drivers prefixes ("HDF5:")
QString QgsRasterLayer:: encodedSource(const QString& source,
const QgsReadWriteContext& context) const override protected
Called by writeLayerXML(), used by derived classes to encode provider's specific data source to project files.
| Parameters | |
|---|---|
| source | data source to encode, typically QgsMapLayer:: |
| context | writing context (e.g. for conversion between relative and absolute paths) |
| Returns | encoded source, typically to be written in the DOM element "datasource" |
Typically resolving absolute or relative paths, usernames and passwords or drivers prefixes ("HDF5:")