QGIS API Documentation
3.14.0-Pi (9f7028fd23)
|
Go to the documentation of this file.
53 #include "qgsgdalprovider.h"
63 #include <QApplication>
66 #include <QDomElement>
71 #include <QFontMetrics>
77 #include <QMessageBox>
83 #define ERR(message) QGS_ERROR_MESSAGE(message,"Raster layer")
103 , QSTRING_NOT_SET( QStringLiteral(
"Not Set" ) )
104 , TRSTRING_NOT_SET( tr(
"Not Set" ) )
113 const QString &baseName,
114 const QString &providerKey,
118 , QSTRING_NOT_SET( QStringLiteral(
"Not Set" ) )
119 , TRSTRING_NOT_SET( tr(
"Not Set" ) )
157 for (
int i = 1; i < mPipe.
size(); i++ )
174 bool myIsValid = QgsGdalProvider::isValidRasterFileName( fileNameQString, retErrMsg );
189 QFileInfo fi(
name );
195 t = fi.lastModified();
218 if ( !mDataProvider )
return 0;
224 if ( !mDataProvider )
return QString();
235 return mDataProvider;
240 return mDataProvider;
283 drawer.
draw( theQPainter, rasterViewPort, qgsMapToPixel );
285 QgsDebugMsgLevel( QStringLiteral(
"total raster draw time (ms): %1" ).arg( time.elapsed(), 5 ), 4 );
290 QList< QPair< QString, QColor > > symbolList;
302 QString myMetadata = QStringLiteral(
"<html><head></head>\n<body>\n" );
305 myMetadata += QStringLiteral(
"<h1>" ) + tr(
"Information from provider" ) + QStringLiteral(
"</h1>\n<hr>\n" ) %
306 QStringLiteral(
"<table class=\"list-view\">\n" ) %
309 QStringLiteral(
"<tr><td class=\"highlight\">" ) % tr(
"Name" ) % QStringLiteral(
"</td><td>" ) %
name() % QStringLiteral(
"</td></tr>\n" );
314 if ( uriComponents.contains( QStringLiteral(
"path" ) ) )
316 path = uriComponents[QStringLiteral(
"path" )].toString();
317 if ( QFile::exists( path ) )
318 myMetadata += QStringLiteral(
"<tr><td class=\"highlight\">" ) % tr(
"Path" ) % QStringLiteral(
"</td><td>%1" ).arg( QStringLiteral(
"<a href=\"%1\">%2</a>" ).arg( QUrl::fromLocalFile( path ).toString(), QDir::toNativeSeparators( path ) ) ) + QStringLiteral(
"</td></tr>\n" );
320 if ( uriComponents.contains( QStringLiteral(
"url" ) ) )
322 const QString url = uriComponents[QStringLiteral(
"url" )].toString();
323 myMetadata += QStringLiteral(
"<tr><td class=\"highlight\">" ) % tr(
"URL" ) % QStringLiteral(
"</td><td>%1" ).arg( QStringLiteral(
"<a href=\"%1\">%2</a>" ).arg( QUrl( url ).toString(), url ) ) + QStringLiteral(
"</td></tr>\n" );
328 myMetadata += QStringLiteral(
"<tr><td class=\"highlight\">" ) % tr(
"Source" ) + QStringLiteral(
"</td><td>%1" ).arg(
publicSource() ) + QStringLiteral(
"</td></tr>\n" );
331 myMetadata += QStringLiteral(
"<tr><td class=\"highlight\">" ) % tr(
"CRS" ) + QStringLiteral(
"</td><td>" );
335 if (
crs().isGeographic() )
336 myMetadata += tr(
"Geographic" );
338 myMetadata += tr(
"Projected" );
340 myMetadata += QStringLiteral(
"</td></tr>\n" ) %
343 QStringLiteral(
"<tr><td class=\"highlight\">" ) % tr(
"Extent" ) % QStringLiteral(
"</td><td>" ) %
extent().
toString() % QStringLiteral(
"</td></tr>\n" ) %
346 QStringLiteral(
"<tr><td class=\"highlight\">" ) % tr(
"Unit" ) % QStringLiteral(
"</td><td>" ) %
QgsUnitTypes::toString(
crs().mapUnits() ) % QStringLiteral(
"</td></tr>\n" ) %
349 QStringLiteral(
"<tr><td class=\"highlight\">" ) % tr(
"Width" ) % QStringLiteral(
"</td><td>" );
351 myMetadata += QString::number(
width() );
353 myMetadata += tr(
"n/a" );
354 myMetadata += QStringLiteral(
"</td></tr>\n" ) %
357 QStringLiteral(
"<tr><td class=\"highlight\">" ) + tr(
"Height" ) + QStringLiteral(
"</td><td>" );
359 myMetadata += QString::number(
height() );
361 myMetadata += tr(
"n/a" );
362 myMetadata += QStringLiteral(
"</td></tr>\n" ) %
365 QStringLiteral(
"<tr><td class=\"highlight\">" ) % tr(
"Data type" ) % QStringLiteral(
"</td><td>" );
370 myMetadata += tr(
"Byte - Eight bit unsigned integer" );
373 myMetadata += tr(
"UInt16 - Sixteen bit unsigned integer " );
376 myMetadata += tr(
"Int16 - Sixteen bit signed integer " );
379 myMetadata += tr(
"UInt32 - Thirty two bit unsigned integer " );
382 myMetadata += tr(
"Int32 - Thirty two bit signed integer " );
385 myMetadata += tr(
"Float32 - Thirty two bit floating point " );
388 myMetadata += tr(
"Float64 - Sixty four bit floating point " );
391 myMetadata += tr(
"CInt16 - Complex Int16 " );
394 myMetadata += tr(
"CInt32 - Complex Int32 " );
397 myMetadata += tr(
"CFloat32 - Complex Float32 " );
400 myMetadata += tr(
"CFloat64 - Complex Float64 " );
403 myMetadata += tr(
"Could not determine raster data type." );
405 myMetadata += QStringLiteral(
"</td></tr>\n" ) %
411 QStringLiteral(
"</table>\n<br><br>" ) %
414 QStringLiteral(
"<h1>" ) % tr(
"Identification" ) % QStringLiteral(
"</h1>\n<hr>\n" ) %
416 QStringLiteral(
"<br><br>\n" ) %
419 QStringLiteral(
"<h1>" ) % tr(
"Extent" ) % QStringLiteral(
"</h1>\n<hr>\n" ) %
421 QStringLiteral(
"<br><br>\n" ) %
424 QStringLiteral(
"<h1>" ) % tr(
"Access" ) % QStringLiteral(
"</h1>\n<hr>\n" ) %
426 QStringLiteral(
"<br><br>\n" ) %
429 QStringLiteral(
"</table>\n<br><br><h1>" ) % tr(
"Bands" ) % QStringLiteral(
"</h1>\n<hr>\n<table class=\"list-view\">\n" ) %
432 QStringLiteral(
"<tr><td class=\"highlight\">" ) % tr(
"Band count" ) % QStringLiteral(
"</td><td>" ) % QString::number(
bandCount() ) % QStringLiteral(
"</td></tr>\n" );
435 myMetadata += QStringLiteral(
"</table>\n<br><table width=\"100%\" class=\"tabular-view\">\n" ) %
436 QStringLiteral(
"<tr><th>" ) % tr(
"Number" ) % QStringLiteral(
"</th><th>" ) % tr(
"Band" ) % QStringLiteral(
"</th><th>" ) % tr(
"No-Data" ) % QStringLiteral(
"</th><th>" ) %
437 tr(
"Min" ) % QStringLiteral(
"</th><th>" ) % tr(
"Max" ) % QStringLiteral(
"</th></tr>\n" );
444 rowClass = QStringLiteral(
"class=\"odd-row\"" );
446 myMetadata += QStringLiteral(
"<tr " ) % rowClass % QStringLiteral(
"><td>" ) % QString::number( i ) % QStringLiteral(
"</td><td>" ) %
bandName( i ) % QStringLiteral(
"</td><td>" );
449 myMetadata += QString::number(
dataProvider()->sourceNoDataValue( i ) );
451 myMetadata += tr(
"n/a" );
452 myMetadata += QStringLiteral(
"</td>" );
457 myMetadata += QStringLiteral(
"<td>" ) % QString::number( myRasterBandStats.
minimumValue,
'f', 10 ) % QStringLiteral(
"</td>" ) %
458 QStringLiteral(
"<td>" ) % QString::number( myRasterBandStats.
maximumValue,
'f', 10 ) % QStringLiteral(
"</td>" );
462 myMetadata += QStringLiteral(
"<td>" ) % tr(
"n/a" ) % QStringLiteral(
"</td><td>" ) % tr(
"n/a" ) % QStringLiteral(
"</td>" );
465 myMetadata += QStringLiteral(
"</tr>\n" );
469 myMetadata += QStringLiteral(
"</table>\n<br><br>" ) %
472 QStringLiteral(
"<h1>" ) % tr(
"Contacts" ) % QStringLiteral(
"</h1>\n<hr>\n" ) %
474 QStringLiteral(
"<br><br>\n" ) %
477 QStringLiteral(
"<h1>" ) % tr(
"References" ) % QStringLiteral(
"</h1>\n<hr>\n" ) %
479 QStringLiteral(
"<br><br>\n" ) %
482 QStringLiteral(
"<h1>" ) % tr(
"History" ) % QStringLiteral(
"</h1>\n<hr>\n" ) %
484 QStringLiteral(
"<br><br>\n" ) %
486 QStringLiteral(
"\n</body>\n</html>\n" );
497 if ( mDataProvider &&
502 QList<QgsColorRampShader::ColorRampItem> myColorRampItemList = mDataProvider->
colorTable( bandNumber );
503 if ( !myColorRampItemList.isEmpty() )
510 QPixmap myPalettePixmap( mySize, mySize );
511 QPainter myQPainter( &myPalettePixmap );
513 QImage myQImage = QImage( mySize, mySize, QImage::Format_RGB32 );
515 myPalettePixmap.fill();
517 double myStep = (
static_cast< double >( myColorRampItemList.size() ) - 1 ) /
static_cast< double >( mySize * mySize );
518 double myValue = 0.0;
519 for (
int myRow = 0; myRow < mySize; myRow++ )
521 QRgb *myLineBuffer =
reinterpret_cast< QRgb *
>( myQImage.scanLine( myRow ) );
522 for (
int myCol = 0; myCol < mySize; myCol++ )
524 myValue = myStep *
static_cast< double >( myCol + myRow * mySize );
526 myShader.
shade( myValue, &c1, &c2, &c3, &c4 );
527 myLineBuffer[ myCol ] = qRgba( c1, c2, c3, c4 );
531 myQPainter.drawImage( 0, 0, myQImage );
532 return myPalettePixmap;
534 QPixmap myNullPixmap;
540 QPixmap myNullPixmap;
558 if ( mDataProvider &&
568 if ( mDataProvider &&
576 void QgsRasterLayer::init()
594 mPipe.
remove( mDataProvider );
595 mDataProvider =
nullptr;
610 if ( !mDataProvider )
617 mDataProvider->setParent(
this );
620 mPipe.
set( mDataProvider );
621 if ( !mDataProvider->
isValid() )
631 QgsDebugMsgLevel( QStringLiteral(
"Set Data provider QgsLayerMetadata identifier[%1]" ).arg(
metadata().identifier() ), 4 );
634 if ( provider == QLatin1String(
"gdal" ) )
666 if ( ( mDataProvider->
bandCount() > 1 ) )
714 QList<QgsColorRampShader::ColorRampItem> colorTable = mDataProvider->
colorTable( 1 );
737 for (
int bandNo = 1; bandNo <= mDataProvider->
bandCount(); bandNo++ )
764 QString resampling = settings.
value( QStringLiteral(
"/Raster/defaultZoomedInResampling" ), QStringLiteral(
"nearest neighbour" ) ).toString();
765 if ( resampling == QStringLiteral(
"bilinear" ) )
769 else if ( resampling == QStringLiteral(
"cubic" ) )
773 resampling = settings.
value( QStringLiteral(
"/Raster/defaultZoomedOutResampling" ), QStringLiteral(
"nearest neighbour" ) ).toString();
774 if ( resampling == QStringLiteral(
"bilinear" ) )
783 mPipe.
set( projector );
831 QDomImplementation domImplementation;
832 QDomDocumentType documentType;
836 if ( hadRenderer && ! loadDefaultStyleFlag )
838 documentType = domImplementation.createDocumentType(
839 QStringLiteral(
"qgis" ), QStringLiteral(
"http://mrcc.com/qgis.dtd" ), QStringLiteral(
"SYSTEM" ) );
841 QDomDocument doc = QDomDocument( documentType );
842 QDomElement styleElem = doc.createElement( QStringLiteral(
"qgis" ) );
843 styleElem.setAttribute( QStringLiteral(
"version" ),
Qgis::version() );
847 QgsDebugMsg( QStringLiteral(
"Could not store symbology for layer %1: %2" )
853 doc.appendChild( styleElem );
855 mOriginalStyleDocument = doc;
856 mOriginalStyleElement = styleElem;
865 for (
int i = mPipe.
size() - 1; i >= 0; --i )
881 bool defaultLoadedFlag =
false;
882 bool restoredStyle =
false;
883 if ( loadDefaultStyleFlag )
887 else if ( !mOriginalStyleElement.isNull() )
890 if ( !
readSymbology( mOriginalStyleElement, errorMsg, readContext ) )
892 QgsDebugMsg( QStringLiteral(
"Could not restore symbology for layer %1: %2" )
899 restoredStyle =
true;
906 if ( !defaultLoadedFlag && !restoredStyle )
915 void QgsRasterLayer::closeDataProvider()
918 mPipe.
remove( mDataProvider );
919 mDataProvider =
nullptr;
922 void QgsRasterLayer::computeMinMax(
int band,
927 double &min,
double &max )
930 min = std::numeric_limits<double>::quiet_NaN();
931 max = std::numeric_limits<double>::quiet_NaN();
932 if ( !mDataProvider )
951 QgsDebugMsgLevel( QStringLiteral(
"myLower = %1 myUpper = %2" ).arg( myLower ).arg( myUpper ), 4 );
954 QgsDebugMsgLevel( QStringLiteral(
"band = %1 min = %2 max = %3" ).arg( band ).arg( min ).arg( max ), 4 );
960 return mDataProvider ? mDataProvider->
ignoreExtents() :
false;
965 return mTemporalProperties;
974 generateLookupTableFlag,
982 bool generateLookupTableFlag,
986 if ( !rasterRenderer || !mDataProvider )
992 QList<QgsContrastEnhancement *> myEnhancements;
998 QString rendererType = rasterRenderer->
type();
999 if ( rendererType == QLatin1String(
"singlebandgray" ) )
1002 if ( !myGrayRenderer )
1006 myBands << myGrayRenderer->
grayBand();
1007 myRasterRenderer = myGrayRenderer;
1010 else if ( rendererType == QLatin1String(
"multibandcolor" ) )
1013 if ( !myMultiBandRenderer )
1018 myRasterRenderer = myMultiBandRenderer;
1021 else if ( rendererType == QLatin1String(
"singlebandpseudocolor" ) )
1024 if ( !myPseudoColorRenderer )
1028 myBands << myPseudoColorRenderer->
band();
1029 myRasterRenderer = myPseudoColorRenderer;
1030 myMinMaxOrigin = myPseudoColorRenderer->
minMaxOrigin();
1037 const auto constMyBands = myBands;
1038 for (
int myBand : constMyBands )
1044 myEnhancement->setContrastEnhancementAlgorithm(
algorithm, generateLookupTableFlag );
1048 computeMinMax( myBand, myMinMaxOrigin, limits,
extent, sampleSize, min, max );
1050 if ( rendererType == QLatin1String(
"singlebandpseudocolor" ) )
1054 if ( myPseudoColorRenderer->
shader() )
1057 if ( colorRampShader )
1065 myEnhancement->setMinimumValue( min );
1066 myEnhancement->setMaximumValue( max );
1067 myEnhancements.append( myEnhancement.release() );
1072 myEnhancements.append(
nullptr );
1076 if ( rendererType == QLatin1String(
"singlebandgray" ) )
1080 else if ( rendererType == QLatin1String(
"multibandcolor" ) )
1088 qDeleteAll( myEnhancements );
1096 if ( myRasterRenderer )
1101 if ( rasterRenderer ==
renderer() )
1153 if ( mDataProvider &&
1154 mLastRectangleUsedByRefreshContrastEnhancementIfNeeded !=
extent &&
1158 refreshRenderer( rasterRenderer,
extent );
1164 if ( mDataProvider )
1180 mLastRectangleUsedByRefreshContrastEnhancementIfNeeded =
extent;
1183 computeMinMax( sbpcr->
band(),
1193 if ( colorRampShader )
1206 if ( colorRampShader )
1221 mLastRectangleUsedByRefreshContrastEnhancementIfNeeded =
extent;
1231 if ( singleBandRenderer )
1233 else if ( multiBandRenderer )
1257 if ( !
mValid || !mDataProvider )
1259 QgsDebugMsgLevel( QStringLiteral(
"invoked with invalid layer or null mDataProvider" ), 3 );
1260 return customProperty( QStringLiteral(
"storedSubsetString" ) ).toString();
1271 if ( !
mValid || !mDataProvider )
1273 QgsDebugMsgLevel( QStringLiteral(
"invoked with invalid layer or null mDataProvider or while editing" ), 3 );
1309 QString defaultLimits;
1314 key = QStringLiteral(
"singleBand" );
1324 key = QStringLiteral(
"multiBandSingleByte" );
1332 key = QStringLiteral(
"multiBandMultiByte" );
1340 if ( key.isEmpty() )
1342 QgsDebugMsgLevel( QStringLiteral(
"No default contrast enhancement for this drawing style" ), 2 );
1349 QString myAlgorithmString = mySettings.
value(
"/Raster/defaultContrastEnhancementAlgorithm/" + key, defaultAlg ).toString();
1354 QString myLimitsString = mySettings.
value(
"/Raster/defaultContrastEnhancementLimits/" + key, defaultLimits ).toString();
1376 if ( mDataProvider )
1378 QgsDebugMsgLevel( QStringLiteral(
"About to mDataProvider->setLayerOrder(layers)." ), 4 );
1387 if ( mDataProvider )
1389 QgsDebugMsgLevel( QStringLiteral(
"About to mDataProvider->setSubLayerVisibility(name, vis)." ), 4 );
1397 if ( !mDataProvider )
1415 Q_UNUSED( errorMessage )
1427 QDomElement constraintElem = doc.createElement( QStringLiteral(
"sld:LayerFeatureConstraints" ) );
1428 node.appendChild( constraintElem );
1430 QDomElement featureTypeConstraintElem = doc.createElement( QStringLiteral(
"sld:FeatureTypeConstraint" ) );
1431 constraintElem.appendChild( featureTypeConstraintElem );
1433 QDomElement userStyleElem = doc.createElement( QStringLiteral(
"sld:UserStyle" ) );
1434 node.appendChild( userStyleElem );
1436 if ( !
name().isEmpty() )
1438 QDomElement nameElem = doc.createElement( QStringLiteral(
"sld:Name" ) );
1439 nameElem.appendChild( doc.createTextNode(
name() ) );
1440 userStyleElem.appendChild( nameElem );
1443 if ( !
abstract().isEmpty() )
1445 QDomElement abstractElem = doc.createElement( QStringLiteral(
"sld:Abstract" ) );
1446 abstractElem.appendChild( doc.createTextNode(
abstract() ) );
1447 userStyleElem.appendChild( abstractElem );
1450 if ( !
title().isEmpty() )
1452 QDomElement titleElem = doc.createElement( QStringLiteral(
"sld:Title" ) );
1453 titleElem.appendChild( doc.createTextNode(
title() ) );
1454 userStyleElem.appendChild( titleElem );
1457 QDomElement featureTypeStyleElem = doc.createElement( QStringLiteral(
"sld:FeatureTypeStyle" ) );
1458 userStyleElem.appendChild( featureTypeStyleElem );
1468 QDomElement typeStyleNameElem = doc.createElement( QStringLiteral(
"sld:Name" ) );
1469 featureTypeStyleElem.appendChild( typeStyleNameElem );
1472 QDomElement typeStyleRuleElem = doc.createElement( QStringLiteral(
"sld:Rule" ) );
1473 featureTypeStyleElem.appendChild( typeStyleRuleElem );
1481 QDomElement minScaleElem = doc.createElement( QStringLiteral(
"sld:MinScaleDenominator" ) );
1482 minScaleElem.appendChild( doc.createTextNode( QString::number(
maximumScale() ) ) );
1483 typeStyleRuleElem.appendChild( minScaleElem );
1486 QDomElement maxScaleElem = doc.createElement( QStringLiteral(
"sld:MaxScaleDenominator" ) );
1487 maxScaleElem.appendChild( doc.createTextNode( QString::number(
minimumScale() ) ) );
1488 typeStyleRuleElem.appendChild( maxScaleElem );
1492 mPipe.
renderer()->
toSld( doc, typeStyleRuleElem, localProps );
1497 QDomNodeList elements = typeStyleRuleElem.elementsByTagName( QStringLiteral(
"sld:RasterSymbolizer" ) );
1498 if ( elements.size() != 0 )
1501 QDomElement rasterSymbolizerElem = elements.at( 0 ).toElement();
1504 auto vendorOptionWriter = [&]( QString
name, QString value )
1506 QDomElement vendorOptionElem = doc.createElement( QStringLiteral(
"sld:VendorOption" ) );
1507 vendorOptionElem.setAttribute( QStringLiteral(
"name" ),
name );
1508 vendorOptionElem.appendChild( doc.createTextNode( value ) );
1509 rasterSymbolizerElem.appendChild( vendorOptionElem );
1519 property = QStringLiteral(
"lightness" );
1522 property = QStringLiteral(
"luminosity" );
1525 property = QStringLiteral(
"average" );
1531 if ( !property.isEmpty() )
1532 vendorOptionWriter( QStringLiteral(
"grayScale" ), property );
1538 vendorOptionWriter( QStringLiteral(
"colorizeOn" ), QString::number(
hueSaturationFilter()->colorizeOn() ) );
1539 vendorOptionWriter( QStringLiteral(
"colorizeRed" ), QString::number(
hueSaturationFilter()->colorizeColor().red() ) );
1540 vendorOptionWriter( QStringLiteral(
"colorizeGreen" ), QString::number(
hueSaturationFilter()->colorizeColor().green() ) );
1541 vendorOptionWriter( QStringLiteral(
"colorizeBlue" ), QString::number(
hueSaturationFilter()->colorizeColor().blue() ) );
1543 vendorOptionWriter( QStringLiteral(
"colorizeStrength" ), QString::number(
hueSaturationFilter()->colorizeStrength() / 100.0 ) );
1544 vendorOptionWriter( QStringLiteral(
"saturation" ), QString::number(
hueSaturationFilter()->colorizeColor().saturationF() ) );
1553 double sF = ( s - ( -100.0 ) ) / ( 100.0 - ( -100.0 ) );
1554 vendorOptionWriter( QStringLiteral(
"saturation" ), QString::number( sF ) );
1563 double bF = ( b - ( -255.0 ) ) / ( 255.0 - ( -255.0 ) );
1564 vendorOptionWriter( QStringLiteral(
"brightness" ), QString::number( bF ) );
1572 double cF = (
c - ( -100.0 ) ) / ( 100.0 - ( -100.0 ) );
1573 vendorOptionWriter( QStringLiteral(
"contrast" ), QString::number( cF ) );
1587 if ( newProps.contains( QStringLiteral(
"contrast" ) ) )
1590 double contrast = newProps[ QStringLiteral(
"contrast" ) ].toDouble();
1591 double percentage = ( contrast - ( -100.0 ) ) / ( 100.0 - ( -100.0 ) );
1592 if ( percentage <= 0.5 )
1595 gamma = percentage / 0.5;
1602 QDomElement globalContrastEnhancementElem = doc.createElement( QStringLiteral(
"sld:ContrastEnhancement" ) );
1603 rasterSymolizerElem.appendChild( globalContrastEnhancementElem );
1605 QDomElement gammaValueElem = doc.createElement( QStringLiteral(
"sld:GammaValue" ) );
1606 gammaValueElem.appendChild( doc.createTextNode( QString::number( gamma ) ) );
1607 globalContrastEnhancementElem.appendChild( gammaValueElem );
1640 if ( mDataProvider )
1646 if ( ! mDataProvider )
1647 return QStringList();
1655 QImage image( size, format );
1660 if ( image.format() == QImage::Format_Indexed8 )
1662 image.setColor( 0, bgColor.rgba() );
1667 image.fill( bgColor );
1672 double mapUnitsPerPixel;
1678 mapUnitsPerPixel =
extent.
width() / image.width();
1679 y = ( image.height() -
extent.
height() / mapUnitsPerPixel ) / 2;
1684 x = ( image.width() -
extent.
width() / mapUnitsPerPixel ) / 2;
1687 const double pixelWidth =
extent.
width() / mapUnitsPerPixel;
1688 const double pixelHeight =
extent.
height() / mapUnitsPerPixel;
1692 rasterViewPort->
mWidth = image.width();
1693 rasterViewPort->
mHeight = image.height();
1701 QPainter *painter =
new QPainter( &image );
1702 draw( painter, rasterViewPort, mapToPixel );
1703 delete rasterViewPort;
1725 Q_UNUSED( errorMessage )
1728 QDomElement rasterRendererElem;
1730 QDomElement layerElement = layer_node.toElement();
1737 QDomNode pipeNode = layer_node.firstChildElement( QStringLiteral(
"pipe" ) );
1738 if ( pipeNode.isNull() )
1740 pipeNode = layer_node;
1744 if ( !layer_node.firstChildElement( QStringLiteral(
"rasterproperties" ) ).isNull() )
1747 QDomNode layerNodeCopy = layer_node.cloneNode();
1748 QDomDocument doc = layerNodeCopy.ownerDocument();
1749 QDomElement rasterPropertiesElem = layerNodeCopy.firstChildElement( QStringLiteral(
"rasterproperties" ) );
1752 rasterRendererElem = layerNodeCopy.firstChildElement( QStringLiteral(
"rasterrenderer" ) );
1757 rasterRendererElem = pipeNode.firstChildElement( QStringLiteral(
"rasterrenderer" ) );
1760 if ( !rasterRendererElem.isNull() )
1762 QString rendererType = rasterRendererElem.attribute( QStringLiteral(
"type" ) );
1776 QDomElement brightnessElem = pipeNode.firstChildElement( QStringLiteral(
"brightnesscontrast" ) );
1777 if ( !brightnessElem.isNull() )
1787 QDomElement hueSaturationElem = pipeNode.firstChildElement( QStringLiteral(
"huesaturation" ) );
1788 if ( !hueSaturationElem.isNull() )
1798 QDomElement resampleElem = pipeNode.firstChildElement( QStringLiteral(
"rasterresampler" ) );
1799 if ( !resampleElem.isNull() )
1805 QDomNode blendModeNode = layer_node.namedItem( QStringLiteral(
"blendMode" ) );
1806 if ( !blendModeNode.isNull() )
1808 QDomElement e = blendModeNode.toElement();
1819 return readSymbology( node, errorMessage, context, categories );
1828 QDomNode pkeyNode = layer_node.namedItem( QStringLiteral(
"provider" ) );
1830 if ( pkeyNode.isNull() )
1836 QDomElement pkeyElt = pkeyNode.toElement();
1850 QDomNode rpNode = layer_node.namedItem( QStringLiteral(
"rasterproperties" ) );
1856 if ( !
mDataSource.contains( QLatin1String(
"crs=" ) ) && !
mDataSource.contains( QLatin1String(
"format=" ) ) )
1858 QgsDebugMsgLevel( QStringLiteral(
"Old WMS URI format detected -> adding params" ), 4 );
1861 QDomElement layerElement = rpNode.firstChildElement( QStringLiteral(
"wmsSublayer" ) );
1862 while ( !layerElement.isNull() )
1867 uri.
setParam( QStringLiteral(
"layers" ), layerElement.namedItem( QStringLiteral(
"name" ) ).toElement().text() );
1870 uri.
setParam( QStringLiteral(
"styles" ), layerElement.namedItem( QStringLiteral(
"style" ) ).toElement().text() );
1872 layerElement = layerElement.nextSiblingElement( QStringLiteral(
"wmsSublayer" ) );
1876 uri.
setParam( QStringLiteral(
"format" ), rpNode.namedItem( QStringLiteral(
"wmsFormat" ) ).toElement().text() );
1880 uri.
setParam( QStringLiteral(
"crs" ),
crs().authid() );
1892 mOriginalStyleElement = layer_node.namedItem( QStringLiteral(
"originalStyle" ) ).firstChildElement();
1893 if ( mOriginalStyleElement.isNull() )
1894 mOriginalStyleElement = layer_node.toElement();
1895 mOriginalStyleDocument = layer_node.ownerDocument();
1897 if ( ! mDataProvider )
1921 QDomNode stampNode = layer_node.namedItem(
"timestamp" );
1922 if ( !stampNode.isNull() )
1924 QDateTime stamp = QDateTime::fromString( stampNode.toElement().text(), Qt::ISODate );
1926 if ( stamp < mDataProvider->dataTimestamp() )
1929 closeDataProvider();
1932 if ( !
mValid )
return false;
1938 QDomElement noDataElement = layer_node.firstChildElement( QStringLiteral(
"noData" ) );
1940 QDomNodeList noDataBandList = noDataElement.elementsByTagName( QStringLiteral(
"noDataList" ) );
1942 for (
int i = 0; i < noDataBandList.size(); ++i )
1944 QDomElement bandElement = noDataBandList.at( i ).toElement();
1946 int bandNo = bandElement.attribute( QStringLiteral(
"bandNo" ) ).toInt( &ok );
1948 if ( ok && ( bandNo > 0 ) && ( bandNo <= mDataProvider->
bandCount() ) )
1950 mDataProvider->
setUseSourceNoDataValue( bandNo, bandElement.attribute( QStringLiteral(
"useSrcNoData" ) ).toInt() );
1953 QDomNodeList rangeList = bandElement.elementsByTagName( QStringLiteral(
"noDataRange" ) );
1955 myNoDataRangeList.reserve( rangeList.size() );
1956 for (
int j = 0; j < rangeList.size(); ++j )
1958 QDomElement rangeElement = rangeList.at( j ).toElement();
1959 QgsRasterRange myNoDataRange( rangeElement.attribute( QStringLiteral(
"min" ) ).toDouble(),
1960 rangeElement.attribute( QStringLiteral(
"max" ) ).toDouble() );
1961 QgsDebugMsgLevel( QStringLiteral(
"min = %1 %2" ).arg( rangeElement.attribute(
"min" ) ).arg( myNoDataRange.
min() ), 4 );
1962 myNoDataRangeList << myNoDataRange;
1976 Q_UNUSED( errorMessage )
1979 QDomElement layerElement = layer_node.toElement();
1984 QDomElement pipeElement = document.createElement( QStringLiteral(
"pipe" ) );
1986 for (
int i = 1; i < mPipe.
size(); i++ )
1989 if ( !interface )
continue;
1990 interface->
writeXml( document, pipeElement );
1993 layer_node.appendChild( pipeElement );
1995 if ( !
isValid() && !mOriginalStyleElement.isNull() )
1997 QDomElement originalStyleElement = document.createElement( QStringLiteral(
"originalStyle" ) );
1998 originalStyleElement.appendChild( mOriginalStyleElement );
1999 layer_node.appendChild( originalStyleElement );
2003 QDomElement blendModeElement = document.createElement( QStringLiteral(
"blendMode" ) );
2005 blendModeElement.appendChild( blendModeText );
2006 layer_node.appendChild( blendModeElement );
2013 return writeSymbology( node, doc, errorMessage, context, categories );
2021 QDomDocument &document,
2026 QDomElement mapLayerNode = layer_node.toElement();
2028 if ( mapLayerNode.isNull() ||
"maplayer" != mapLayerNode.nodeName() )
2034 mapLayerNode.setAttribute( QStringLiteral(
"type" ), QStringLiteral(
"raster" ) );
2038 QDomElement provider = document.createElement( QStringLiteral(
"provider" ) );
2039 QDomText providerText = document.createTextNode(
mProviderKey );
2040 provider.appendChild( providerText );
2041 layer_node.appendChild( provider );
2044 QDomElement noData = document.createElement( QStringLiteral(
"noData" ) );
2046 for (
int bandNo = 1; bandNo <= mDataProvider->
bandCount(); bandNo++ )
2048 QDomElement noDataRangeList = document.createElement( QStringLiteral(
"noDataList" ) );
2049 noDataRangeList.setAttribute( QStringLiteral(
"bandNo" ), bandNo );
2050 noDataRangeList.setAttribute( QStringLiteral(
"useSrcNoData" ), mDataProvider->
useSourceNoDataValue( bandNo ) );
2052 const auto constUserNoDataValues = mDataProvider->
userNoDataValues( bandNo );
2055 QDomElement noDataRange = document.createElement( QStringLiteral(
"noDataRange" ) );
2059 noDataRangeList.appendChild( noDataRange );
2062 noData.appendChild( noDataRangeList );
2065 if ( noData.hasChildNodes() )
2067 layer_node.appendChild( noData );
2074 return writeSymbology( layer_node, document, errorMsg, context );
2078 static bool _parseGpkgColons(
const QString &src, QString &filename, QString &tablename )
2083 QStringList lst = src.split(
':' );
2084 if ( lst.count() != 3 && lst.count() != 4 )
2087 tablename = lst.last();
2088 if ( lst.count() == 3 )
2093 else if ( lst.count() == 4 && lst[1].count() == 1 && ( lst[2][0] ==
'/' || lst[2][0] ==
'\\' ) )
2096 filename = lst[1] +
":" + lst[2];
2106 bool handled =
false;
2111 if ( src.startsWith( QLatin1String(
"NETCDF:" ) ) )
2115 QRegExp r(
"NETCDF:(.+):([^:]+)" );
2116 if ( r.exactMatch( src ) )
2118 QString filename = r.cap( 1 );
2119 if ( filename.startsWith(
'"' ) && filename.endsWith(
'"' ) )
2120 filename = filename.mid( 1, filename.length() - 2 );
2125 else if ( src.startsWith( QLatin1String(
"GPKG:" ) ) )
2128 QString filename, tablename;
2129 if ( _parseGpkgColons( src, filename, tablename ) )
2132 src = QStringLiteral(
"GPKG:%1:%2" ).arg( filename, tablename );
2136 else if ( src.startsWith( QLatin1String(
"HDF4_SDS:" ) ) )
2140 QRegExp r(
"HDF4_SDS:([^:]+):(.+):([^:]+)" );
2141 if ( r.exactMatch( src ) )
2143 QString filename = r.cap( 2 );
2144 if ( filename.startsWith(
'"' ) && filename.endsWith(
'"' ) )
2145 filename = filename.mid( 1, filename.length() - 2 );
2146 src =
"HDF4_SDS:" + r.cap( 1 ) +
":\"" + context.
pathResolver().
writePath( filename ) +
"\":" + r.cap( 3 );
2150 else if ( src.startsWith( QLatin1String(
"HDF5:" ) ) )
2154 QRegExp r(
"HDF5:(.+):([^:]+)" );
2155 if ( r.exactMatch( src ) )
2157 QString filename = r.cap( 1 );
2158 if ( filename.startsWith(
'"' ) && filename.endsWith(
'"' ) )
2159 filename = filename.mid( 1, filename.length() - 2 );
2164 else if ( src.contains( QRegExp(
"^(NITF_IM|RADARSAT_2_CALIB):" ) ) )
2168 QRegExp r(
"([^:]+):([^:]+):(.+)" );
2169 if ( r.exactMatch( src ) )
2181 QUrl srcUrl( uri.
param( QStringLiteral(
"url" ) ) );
2182 if ( srcUrl.isLocalFile() )
2187 uri.
setParam( QStringLiteral(
"url" ), QUrl::fromLocalFile( relSrcUrl ).toString() );
2203 if ( provider == QLatin1String(
"wms" ) )
2217 if ( !src.contains( QLatin1String(
"type=" ) ) &&
2218 !src.contains( QLatin1String(
"crs=" ) ) && !src.contains( QLatin1String(
"format=" ) ) )
2220 QgsDebugMsgLevel( QStringLiteral(
"Old WMS URI format detected -> converting to new format" ), 2 );
2222 if ( !src.startsWith( QLatin1String(
"http:" ) ) )
2224 QStringList parts = src.split(
',' );
2225 QStringListIterator iter( parts );
2226 while ( iter.hasNext() )
2228 QString item = iter.next();
2229 if ( item.startsWith( QLatin1String(
"username=" ) ) )
2233 else if ( item.startsWith( QLatin1String(
"password=" ) ) )
2237 else if ( item.startsWith( QLatin1String(
"tiled=" ) ) )
2243 QStringList params = item.mid( 6 ).split(
';' );
2245 if ( params.size() == 2 )
2247 uri.
setParam( QStringLiteral(
"maxWidth" ), params.takeFirst() );
2248 uri.
setParam( QStringLiteral(
"maxHeight" ), params.takeFirst() );
2250 else if ( params.size() > 2 )
2254 uri.
setParam( QStringLiteral(
"tileMatrixSet" ), QString() );
2257 else if ( item.startsWith( QLatin1String(
"featureCount=" ) ) )
2259 uri.
setParam( QStringLiteral(
"featureCount" ), item.mid( 13 ) );
2261 else if ( item.startsWith( QLatin1String(
"url=" ) ) )
2263 uri.
setParam( QStringLiteral(
"url" ), item.mid( 4 ) );
2265 else if ( item.startsWith( QLatin1String(
"ignoreUrl=" ) ) )
2267 uri.
setParam( QStringLiteral(
"ignoreUrl" ), item.mid( 10 ).split(
';' ) );
2273 uri.
setParam( QStringLiteral(
"url" ), src );
2284 QUrl srcUrl( uri.
param( QStringLiteral(
"url" ) ) );
2285 if ( srcUrl.isLocalFile() )
2289 uri.
setParam( QStringLiteral(
"url" ), QUrl::fromLocalFile( absSrcUrl ).toString() );
2296 bool handled =
false;
2298 if ( provider == QLatin1String(
"gdal" ) )
2300 if ( src.startsWith( QLatin1String(
"NETCDF:" ) ) )
2304 QRegExp r(
"NETCDF:(.+):([^:]+)" );
2305 if ( r.exactMatch( src ) )
2307 QString filename = r.cap( 1 );
2308 if ( filename.startsWith(
'"' ) && filename.endsWith(
'"' ) )
2309 filename = filename.mid( 1, filename.length() - 2 );
2314 else if ( src.startsWith( QLatin1String(
"GPKG:" ) ) )
2317 QString filename, tablename;
2318 if ( _parseGpkgColons( src, filename, tablename ) )
2321 src = QStringLiteral(
"GPKG:%1:%2" ).arg( filename, tablename );
2325 else if ( src.startsWith( QLatin1String(
"HDF4_SDS:" ) ) )
2329 QRegExp r(
"HDF4_SDS:([^:]+):(.+):([^:]+)" );
2330 if ( r.exactMatch( src ) )
2332 QString filename = r.cap( 2 );
2333 if ( filename.startsWith(
'"' ) && filename.endsWith(
'"' ) )
2334 filename = filename.mid( 1, filename.length() - 2 );
2335 src =
"HDF4_SDS:" + r.cap( 1 ) +
":\"" + context.
pathResolver().
readPath( filename ) +
"\":" + r.cap( 3 );
2339 else if ( src.startsWith( QLatin1String(
"HDF5:" ) ) )
2343 QRegExp r(
"HDF5:(.+):([^:]+)" );
2344 if ( r.exactMatch( src ) )
2346 QString filename = r.cap( 1 );
2347 if ( filename.startsWith(
'"' ) && filename.endsWith(
'"' ) )
2348 filename = filename.mid( 1, filename.length() - 2 );
2353 else if ( src.contains( QRegExp(
"^(NITF_IM|RADARSAT_2_CALIB):" ) ) )
2357 QRegExp r(
"([^:]+):([^:]+):(.+)" );
2358 if ( r.exactMatch( src ) )
2375 if ( !mDataProvider )
return 0;
2376 return mDataProvider->
xSize();
2381 if ( !mDataProvider )
return 0;
2382 return mDataProvider->
ySize();
2390 bool QgsRasterLayer::update()
2397 closeDataProvider();
void setContrastEnhancement(QgsContrastEnhancement *ce)
Takes ownership.
void setError(const QgsError &error)
Sets error message.
void willBeDeleted()
Emitted in the destructor when the layer is about to be deleted, but it is still in a perfectly valid...
static QgsRasterRendererRegistry * rasterRendererRegistry()
Returns the application's raster renderer registry, used for managing raster layer renderers.
QgsPointXY mBottomRightPoint
Coordinate (in output device coordinate system) of bottom right corner of the part of the raster that...
virtual bool hasStatistics(int bandNo, int stats=QgsRasterBandStats::All, const QgsRectangle &extent=QgsRectangle(), int sampleSize=0)
Returns true if histogram is available (cached, already calculated).
void setGreenContrastEnhancement(QgsContrastEnhancement *ce)
Takes ownership.
virtual void setUserNoDataValue(int bandNo, const QgsRasterRangeList &noData)
QgsCoordinateReferenceSystem crs
void readCommonStyle(const QDomElement &layerElement, const QgsReadWriteContext &context, StyleCategories categories=AllStyleCategories)
Read style data common to all layer types.
static QString printValue(double value)
Print double value with all necessary significant digits.
@ Float32
Thirty two bit floating point (float)
QPixmap paletteAsPixmap(int bandNumber=1)
Returns a 100x100 pixmap of the color palette.
int bandCount() const
Returns the number of bands in this layer.
virtual QString generateBandName(int bandNumber) const
helper function to create zero padded band names
bool writeSymbology(QDomNode &, QDomDocument &doc, QString &errorMessage, const QgsReadWriteContext &context, QgsMapLayer::StyleCategories categories=QgsMapLayer::AllStyleCategories) const override
DataType
Raster data types.
static QString version()
Version string.
void configChanged()
Emitted whenever the configuration is changed.
@ UInt32
Thirty two bit unsigned integer (quint32)
virtual bool supportsSubsetString() const
Returns true if the provider supports setting of subset strings.
Qgis::DataType dataType(int bandNo) const override=0
Returns data type for the band specified by number.
Setting options for creating vector data providers.
BlendMode
Blending modes enum defining the available composition modes that can be used when rendering a layer.
QVariant value(const QString &key, const QVariant &defaultValue=QVariant(), Section section=NoSection) const
Returns the value for setting key.
virtual void writeXml(QDomDocument &doc, QDomElement &parentElem) const
Write base class members to xml.
bool ignoreExtents() const
If the ignoreExtent flag is set, the layer will also render outside the bounding box reported by the ...
virtual QgsRasterBandStats bandStatistics(int bandNo, int stats=QgsRasterBandStats::All, const QgsRectangle &extent=QgsRectangle(), int sampleSize=0, QgsRasterBlockFeedback *feedback=nullptr)
Returns the band statistics.
void setLayerOrder(const QStringList &layers) override
Reorders the previously selected sublayers of this layer from bottom to top.
@ SingleBandColorDataStyle
const QgsRasterMinMaxOrigin & minMaxOrigin() const
Returns const reference to origin of min/max values.
bool writeSld(QDomNode &node, QDomDocument &doc, QString &errorMessage, const QgsStringMap &props=QgsStringMap()) const
Writes the symbology of the layer into the document provided in SLD 1.0.0 format.
QString userFriendlyIdentifier(IdentifierType type=MediumString) const
Returns a user friendly identifier for the CRS.
QStringList subLayers() const override
Returns the sublayers of this layer - useful for providers that manage their own layers,...
#define QgsDebugMsgLevel(str, level)
bool readSymbology(const QDomNode &node, QString &errorMessage, QgsReadWriteContext &context, QgsMapLayer::StyleCategories categories=QgsMapLayer::AllStyleCategories) override
virtual bool useSourceNoDataValue(int bandNo) const
Returns the source nodata value usage.
bool isValid() const
Returns the status of the layer.
@ AlphaBand
Alpha (0=transparent, 255=opaque)
bool defaultContrastEnhancementSettings(QgsContrastEnhancement::ContrastEnhancementAlgorithm &myAlgorithm, QgsRasterMinMaxOrigin::Limits &myLimits) const
Returns default contrast enhancement settings for that type of raster.
const QgsContrastEnhancement * redContrastEnhancement() const
virtual void setSubLayerVisibility(const QString &name, bool vis)
Set the visibility of the given sublayer name.
virtual QgsMapLayer * clone() const =0
Returns a new instance equivalent to this one except for the id which is still unique.
QPainter::CompositionMode blendMode() const
Returns the current blending mode for a layer.
void setDefaultContrastEnhancement()
Sets the default contrast enhancement.
Limits
This enumerator describes the limits used to compute min/max values.
Q_INVOKABLE void setCustomProperty(const QString &key, const QVariant &value)
Set a custom property for layer.
As part of the API refactoring and improvements which landed in the Processing API was substantially reworked from the x version This was done in order to allow much of the underlying Processing framework to be ported into allowing algorithms to be written in pure substantial changes are required in order to port existing x Processing algorithms for QGIS x The most significant changes are outlined not GeoAlgorithm For algorithms which operate on features one by consider subclassing the QgsProcessingFeatureBasedAlgorithm class This class allows much of the boilerplate code for looping over features from a vector layer to be bypassed and instead requires implementation of a processFeature method Ensure that your algorithm(or algorithm 's parent class) implements the new pure virtual createInstance(self) call
@ WKT_PREFERRED
Preferred format, matching the most recent WKT ISO standard. Currently an alias to WKT2_2019,...
virtual void cumulativeCut(int bandNo, double lowerCount, double upperCount, double &lowerValue, double &upperValue, const QgsRectangle &extent=QgsRectangle(), int sampleSize=0)
Find values for cumulative pixel count cut.
QgsMapLayer::ReadFlags mReadFlags
Read flags. It's up to the subclass to respect these when restoring state from XML.
void setShader(QgsRasterShader *shader)
Takes ownership of the shader.
virtual bool setSubsetString(const QString &subset, bool updateFeatureCount=true)
Set the subset string used to create a subset of features in the layer.
bool skipCrsValidation
Controls whether the layer is allowed to have an invalid/unknown CRS.
bool set(QgsRasterInterface *interface)
Insert a new known interface in default place or replace interface of the same role if it already exi...
QgsRasterShaderFunction * rasterShaderFunction()
virtual bool accept(QgsStyleEntityVisitorInterface *visitor) const
Accepts the specified symbology visitor, causing it to visit all symbols associated with the renderer...
QgsCoordinateReferenceSystem mSrcCRS
Source coordinate system.
QDateTime dataTimestamp() const override
Current time stamp of data source.
static const double SAMPLE_SIZE
Default sample size (number of pixels) for estimated statistics/histogram calculation.
virtual QgsError error() const
Gets current status error.
double mean
The mean cell value for the band. NO_DATA values are excluded.
QgsRectangle extent() const override=0
Returns the extent of the layer.
DrawingStyle
This enumerator describes the different kinds of drawing we can do.
void classifyColorRamp(int classes=0, int band=-1, const QgsRectangle &extent=QgsRectangle(), QgsRasterInterface *input=nullptr)
Classify color ramp shader.
void statusChanged(const QString &status)
Emit a signal with status (e.g. to be caught by QgisApp and display a msg on status bar)
QString decodedSource(const QString &source, const QString &provider, const QgsReadWriteContext &context) const override
Called by readLayerXML(), used by derived classes to decode provider's specific data source from proj...
const QgsContrastEnhancement * greenContrastEnhancement() const
void subsetStringChanged()
Emitted when the layer's subset string has changed.
void setBlendMode(QPainter::CompositionMode blendMode)
Set the blending mode used for rendering a layer.
virtual void setTransformContext(const QgsCoordinateTransformContext &transformContext) override
Sets the coordinate transform context to transformContext.
double stdDevFactor() const
Returns the factor f so that the min/max range is [ mean - f * stddev , mean + f * stddev ].
void readCustomProperties(const QDomNode &layerNode, const QString &keyStartsWith=QString())
Read custom properties from project file.
virtual QString type() const
static const QgsContrastEnhancement::ContrastEnhancementAlgorithm MULTIPLE_BAND_SINGLE_BYTE_ENHANCEMENT_ALGORITHM
Default enhancement algorithm for multiple band raster of type Byte.
QString htmlMetadata() const override
Obtain a formatted HTML string containing assorted metadata for this layer.
QgsPointXY mTopLeftPoint
Coordinate (in output device coordinate system) of top left corner of the part of the raster that is ...
virtual void toSld(QDomDocument &doc, QDomElement &element, const QgsStringMap &props=QgsStringMap()) const
Used from subclasses to create SLD Rule elements following SLD v1.0 specs.
int band() const
Returns the band used by the renderer.
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.
virtual bool setSubsetString(const QString &subset)
Sets the string (typically sql) used to define a subset of the layer.
QgsRasterRendererCreateFunc rendererCreateFunction
QgsCoordinateTransformContext transformContext() const
Returns data provider coordinate transform context.
virtual QString dataSourceUri(bool expandAuthConfig=false) const
Gets the data source specification.
double min() const
Returns the minimum value for the range.
void setRedContrastEnhancement(QgsContrastEnhancement *ce)
Takes ownership.
QImage previewAsImage(QSize size, const QColor &bgColor=Qt::white, QImage::Format format=QImage::Format_ARGB32_Premultiplied)
Draws a preview of the rasterlayer into a QImage.
void refreshContrastEnhancement(const QgsRectangle &extent)
Refresh contrast enhancement with new extent.
virtual void setMetadata(const QgsLayerMetadata &metadata)
Sets the layer's metadata store.
void setCrs(const QgsCoordinateReferenceSystem &srs, bool emitSignal=true)
Sets layer's spatial reference system.
static const QgsContrastEnhancement::ContrastEnhancementAlgorithm SINGLE_BAND_ENHANCEMENT_ALGORITHM
Default enhancement algorithm for single band raster.
static const QgsRasterMinMaxOrigin::Limits MULTIPLE_BAND_MULTI_BYTE_MIN_MAX_LIMITS
Default enhancement limits for multiple band raster of type different from Byte.
QgsLegendColorList legendSymbologyItems() const
Returns a list with classification items (Text and color)
void setRenderer(QgsRasterRenderer *renderer)
Sets the raster's renderer.
@ WholeRaster
Whole raster is used to compute statistics.
QString bandName(int bandNoInt) const
Returns the name of a band given its number.
bool mShouldValidateCrs
true if the layer's CRS should be validated and invalid CRSes are not permitted.
QString mProviderKey
Data provider key (name of the data provider)
@ CFloat32
Complex Float32.
static void mergeScaleDependencies(double mScaleMinDenom, double mScaleMaxDenom, QgsStringMap &props)
Merges the local scale limits, if any, with the ones already in the map, if any.
QgsCoordinateTransformContext transformContext() const
Returns data provider coordinate transform context.
QgsRasterInterface * at(int idx) const
const QgsContrastEnhancement * contrastEnhancement() const
static QgsPainting::BlendMode getBlendModeEnum(QPainter::CompositionMode blendMode)
Returns a BlendMode corresponding to a QPainter::CompositionMode.
QString mLayerName
Name of the layer - used for display.
static bool isValidRasterFileName(const QString &fileNameQString, QString &retError)
This helper checks to see whether the file name appears to be a valid raster file name.
QgsRasterProjector implements approximate projection support for it calculates grid of points in sour...
void setClassificationMax(double max)
double maximumValue
The maximum cell value in the raster band.
QString param(const QString &key) const
Returns a generic parameter value corresponding to the specified key.
void dataSourceChanged()
Emitted whenever the layer's data source has been changed.
void readXml(const QDomElement &filterElem) override
Sets base class members from xml. Usually called from create() methods of subclasses.
@ Discrete
Assigns the color of the higher class for every pixel between two class breaks.
void setUsername(const QString &username)
Sets the username for the URI.
static QString contrastEnhancementAlgorithmString(ContrastEnhancementAlgorithm algorithm)
Returns a string to serialize ContrastEnhancementAlgorithm.
void setBlueContrastEnhancement(QgsContrastEnhancement *ce)
Takes ownership.
@ FlagDontResolveLayers
Don't resolve layer paths or create data providers for layers.
~QgsRasterLayer() override
@ CFloat64
Complex Float64.
QString writePath(const QString &filename) const
Prepare a filename to save it to the project file.
QStringList subLayers() const override
Returns the sublayers of this layer.
bool remove(int idx)
Remove and delete interface at given index if possible.
QgsLayerMetadata metadata
void setColorRampType(QgsColorRampShader::Type colorRampType)
Sets the color ramp type.
int width() const
Returns the width of the (unclipped) raster.
virtual void reloadData()
Reloads the data from the source by calling reloadProviderData() implemented by providers with data c...
static QDateTime lastModified(const QString &name)
Returns time stamp for given file name.
bool mValid
Indicates if the layer is valid and can be drawn.
bool accept(QgsStyleEntityVisitorInterface *visitor) const override
Accepts the specified symbology visitor, causing it to visit all symbols associated with the layer.
ContrastEnhancementAlgorithm
This enumerator describes the types of contrast enhancement algorithms that can be used.
virtual void setExtent(const QgsRectangle &rect)
Sets the extent.
@ CumulativeCut
Range is [ min + cumulativeCutLower() * (max - min), min + cumulativeCutUpper() * (max - min) ].
void draw(QPainter *p, QgsRasterViewPort *viewPort, const QgsMapToPixel *qgsMapToPixel, QgsRasterBlockFeedback *feedback=nullptr)
Draws raster data.
QgsHueSaturationFilter::GrayscaleMode grayscaleMode() const
@ MinMax
Real min-max values.
QString encodedSource(const QString &source, const QgsReadWriteContext &context) const override
Called by writeLayerXML(), used by derived classes to encode provider's specific data source to proje...
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 thumbnailAsPix...
QgsRasterRenderer * renderer() const
virtual int xSize() const
Gets raster size.
void readXml(const QDomElement &filterElem) override
Sets base class members from xml. Usually called from create() methods of subclasses.
@ StretchToMinimumMaximum
virtual QgsRasterDataProvider::ProviderCapabilities providerCapabilities() const
Returns flags containing the supported capabilities of the data provider.
QgsCoordinateTransformContext mTransformContext
Coordinate transform context.
void readStyleManager(const QDomNode &layerNode)
Read style manager's configuration (if any). To be called by subclasses.
static Q_INVOKABLE QString toString(QgsUnitTypes::DistanceUnit unit)
Returns a translated string representing a distance unit.
void writeCommonStyle(QDomElement &layerElement, QDomDocument &document, const QgsReadWriteContext &context, StyleCategories categories=AllStyleCategories) const
Write style data common to all layer types.
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference)
void styleChanged()
Signal emitted whenever a change affects the layer's style.
void repaintRequested(bool deferredUpdate=false)
By emitting this signal the layer tells that either appearance or content have been changed and any v...
int height() const
Returns the height of the (unclipped) raster.
double cumulativeCutLower() const
Returns the lower bound of cumulative cut method (between 0 and 1).
virtual QgsRectangle extent() const
Returns the extent of the layer.
QgsMapLayerTemporalProperties * temporalProperties() override
Returns the layer's temporal properties.
static QPainter::CompositionMode getCompositionMode(QgsPainting::BlendMode blendMode)
Returns a QPainter::CompositionMode corresponding to a BlendMode.
@ ProviderHintBenefitsFromResampling
Provider benefits from resampling and should apply user default resampling settings (since QGIS 3....
const QgsContrastEnhancement * blueContrastEnhancement() const
void setParam(const QString &key, const QString &value)
Sets a generic parameter value on the URI.
void setAlphaBand(int band)
QDateTime timestamp() const override
Time stamp of data source in the moment when data/metadata were loaded by provider.
static Limits limitsFromString(const QString &limits)
Deserialize Limits.
static QString limitsString(Limits limits)
Returns a string to serialize Limits.
virtual QgsRasterInterface * clone() const =0
Clone itself, create deep copy.
virtual QString loadDefaultStyle(bool &resultFlag)
Retrieve the default style for this layer if one exists (either as a .qml file on disk or as a record...
@ ReadLayerMetadata
Provider can read layer metadata from data store. Since QGIS 3.0. See QgsDataProvider::layerMetadata(...
Q_DECL_DEPRECATED void setCrs(const QgsCoordinateReferenceSystem &srcCRS, const QgsCoordinateReferenceSystem &destCRS, int srcDatumTransform=-1, int destDatumTransform=-1)
Sets the source and destination CRS.
QVariantMap decodeUri(const QString &providerKey, const QString &uri)
Breaks a provider data source URI into its component paths (e.g.
bool readXml(const QDomNode &layer_node, QgsReadWriteContext &context) override
Called by readLayerXML(), used by children to read state specific to them from project files.
void setClassificationMin(double min)
QgsCoordinateTransformContext transformContext
Coordinate transform context.
QList< QgsRasterRange > QgsRasterRangeList
QString title() const
Returns the title of the layer used by QGIS Server in GetCapabilities request.
void setZoomedInResampler(QgsRasterResampler *r)
Sets resampler for zoomed in scales. Takes ownership of the object.
virtual QString subsetString() const
Returns the string (typically sql) used to define a subset of the layer.
QString mDataSource
Data source description string, varies by layer type.
void setColorRampItemList(const QList< QgsColorRampShader::ColorRampItem > &list)
Sets a custom colormap.
ContrastEnhancementAlgorithm contrastEnhancementAlgorithm() const
virtual QList< QgsColorRampShader::ColorRampItem > colorTable(int bandNo) const
bool hasScaleBasedVisibility() const
Returns whether scale based visibility is enabled for the layer.
int removeParam(const QString &key)
Removes a generic parameter by key.
@ FullString
Full definition – possibly a very lengthy string, e.g. with no truncation of custom WKT definitions.
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.
@ UInt16
Sixteen bit unsigned integer (quint16)
double minimumScale() const
Returns the minimum map scale (i.e.
void rendererChanged()
Signal emitted when renderer is changed.
double maximumScale() const
Returns the maximum map scale (i.e.
virtual bool ignoreExtents() const
Returns true if the extents reported by the data provider are not reliable and it's possible that the...
virtual int ySize() const
bool readStyle(const QDomNode &node, QString &errorMessage, QgsReadWriteContext &context, QgsMapLayer::StyleCategories categories=QgsMapLayer::AllStyleCategories) override
@ UpdatedCanvas
Constantly updated extent of the canvas is used to compute statistics.
QString toString(int precision=16) const
Returns a string representation of form xmin,ymin : xmax,ymax Coordinates will be truncated to the sp...
void setDefaultsFromDataProviderTemporalCapabilities(const QgsDataProviderTemporalCapabilities *capabilities) override
Sets the layers temporal settings to appropriate defaults based on a provider's temporal capabilities...
double minimumValue
The minimum cell value in the raster band.
static QgsMapLayerLegend * defaultRasterLegend(QgsRasterLayer *rl)
Create new legend implementation for raster layer.
double rasterUnitsPerPixelY() const
Returns the number of raster units per each raster pixel in Y axis.
QDateTime timestamp() const override
Time stamp of data source in the moment when data/metadata were loaded by provider.
QgsRasterResampleFilter * resampleFilter() const
Returns the raster's resample filter.
void dataChanged()
Data of layer changed.
void appendError(const QgsErrorMessage &error)
Add error message.
virtual int colorInterpretation(int bandNo) const
Returns data type for the band specified by number.
void reload() override
Synchronises with changes in the datasource.
virtual void setTransformContext(const QgsCoordinateTransformContext &transformContext)
Sets data coordinate transform context to transformContext.
QString publicSource() const
Gets a version of the internal layer definition that has sensitive bits removed (for example,...
QString readPath(const QString &filename) const
Turn filename read from the project file to an absolute path.
Qgis::DataType sourceDataType(int bandNo) const override=0
Returns source data type for the band specified by number, source data type may be shorter than dataT...
QString source() const
Returns the source for the layer.
void setMinMaxOrigin(const QgsRasterMinMaxOrigin &origin)
Sets origin of min/max values.
Setting options for loading raster layers.
QMap< QString, QString > QgsStringMap
bool loadDefaultStyle
Sets to true if the default layer style should be loaded.
@ ARGB32_Premultiplied
Color, alpha, red, green, blue, 4 bytes the same as QImage::Format_ARGB32_Premultiplied.
void writeStyleManager(QDomNode &layerNode, QDomDocument &doc) const
Write style manager's configuration (if exists). To be called by subclasses.
QgsRasterInterface * last() const
qgssize mHeight
Distance in map units from bottom edge to top edge for the part of the raster that is to be rendered.
virtual QgsRasterRangeList userNoDataValues(int bandNo) const
Returns a list of user no data value ranges.
QgsRasterLayer * clone() const override
Returns a new instance equivalent to this one.
QByteArray encodedUri() const
Returns the complete encoded URI as a byte array.
Q_INVOKABLE QVariant customProperty(const QString &value, const QVariant &defaultValue=QVariant()) const
Read a custom property from layer.
QgsCoordinateTransformContext transformContext() const
Returns the layer data provider coordinate transform context or a default transform context if the la...
virtual void setDataSourceUri(const QString &uri)
Set the data source specification.
QString providerType() const
[ data provider interface ] Which provider is being used for this Raster Layer?
void setEncodedUri(const QByteArray &uri)
Sets the complete encoded uri.
@ StdDev
Range is [ mean - stdDevFactor() * stddev, mean + stdDevFactor() * stddev ].
bool writeXml(QDomNode &layer_node, QDomDocument &doc, const QgsReadWriteContext &context) const override
Called by writeLayerXML(), used by children to write state specific to them to project files.
qgssize mWidth
Width, number of columns to be rendered.
As part of the API refactoring and improvements which landed in the Processing API was substantially reworked from the x version This was done in order to allow much of the underlying Processing framework to be ported into c
void setName(const QString &name)
Set the display name of the layer.
virtual void legendSymbologyItems(QList< QPair< QString, QColor > > &symbolItems) const
Gets symbology items if provided by renderer.
bool shade(double value, int *returnRedValue, int *returnGreenValue, int *returnBlueValue, int *returnAlphaValue) const override
Generates and new RGB value based on one input value.
QgsRasterPipe * pipe()
Returns the raster pipe.
static const QgsContrastEnhancement::ContrastEnhancementAlgorithm MULTIPLE_BAND_MULTI_BYTE_ENHANCEMENT_ALGORITHM
Default enhancement algorithm for multiple band raster of type different from Byte.
static ContrastEnhancementAlgorithm contrastEnhancementAlgorithmFromString(const QString &contrastEnhancementString)
Deserialize ContrastEnhancementAlgorithm.
static int typeSize(int dataType)
virtual QgsRasterInterface * input() const
Current input.
virtual void setUseSourceNoDataValue(int bandNo, bool use)
Sets the source nodata value usage.
void setLimits(QgsRasterMinMaxOrigin::Limits limits)
Sets the limits.
static const QgsRasterMinMaxOrigin::Limits SINGLE_BAND_MIN_MAX_LIMITS
Default enhancement limits for single band raster.
QgsHueSaturationFilter * hueSaturationFilter() const
Returns the raster's hue/saturation filter.
void statusChanged(const QString &) const
Emit a message to be displayed on status bar, usually used by network providers (WMS,...
double height() const
Returns the height of the rectangle.
void refreshRendererIfNeeded(QgsRasterRenderer *rasterRenderer, const QgsRectangle &extent)
Refresh renderer with new extent, if needed.
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::Warning, bool notifyUser=true)
Adds a message to the log instance (and creates it if necessary).
@ Int16
Sixteen bit signed integer (qint16)
QList< QPair< QString, QColor > > QgsLegendColorList
QgsDataProvider * classFactoryFunction_t(const QString *, const QgsDataProvider::ProviderOptions &options)
QgsBrightnessContrastFilter * brightnessFilter() const
Returns the raster's brightness/contrast filter.
Q_DECL_DEPRECATED void setDataProvider(const QString &provider)
Set the data provider.
@ Int32
Thirty two bit signed integer (qint32)
double stdDev
The standard deviation of the cell values.
static const QgsRasterMinMaxOrigin::Limits MULTIPLE_BAND_SINGLE_BYTE_MIN_MAX_LIMITS
Default enhancement limits for multiple band raster of type Byte.
QgsRasterRenderer * renderer() const
Returns the raster's renderer.
void setExtent(QgsRasterMinMaxOrigin::Extent extent)
Sets the extent.
virtual QString subsetString() const
Returns the subset definition string (typically sql) currently in use by the layer and used by the pr...
@ ARGB32
Color, alpha, red, green, blue, 4 bytes the same as QImage::Format_ARGB32.
virtual QgsLayerMetadata layerMetadata() const
Returns layer metadata collected from the provider's source.
void setSubLayerVisibility(const QString &name, bool vis) override
Set the visibility of the given sublayer name.
bool isSpatial() const override
Returns true if the layer is considered a spatial layer, ie it has some form of geometry associated w...
virtual int bandCount() const =0
Gets number of bands.
QgsRasterProjector * projector() const
void setRasterShaderFunction(QgsRasterShaderFunction *function)
A public method that allows the user to set their own shader function.
static QString identifyFormatName(QgsRaster::IdentifyFormat format)
@ CurrentCanvas
Current extent of the canvas (at the time of computation) is used to compute statistics.
QgsRasterMinMaxOrigin::Extent extent() const
Returns the raster extent.
QgsCoordinateReferenceSystem mDestCRS
Target coordinate system.
bool writeStyle(QDomNode &node, QDomDocument &doc, QString &errorMessage, const QgsReadWriteContext &context, QgsMapLayer::StyleCategories categories=QgsMapLayer::AllStyleCategories) const override
QgsRasterShader * shader()
Returns the raster shader.
@ Interpolated
Interpolates the color between two class breaks linearly.
@ Byte
Eight bit unsigned integer (quint8)
@ PaletteIndex
Paletted (see associated color table)
static QgsProviderRegistry * instance(const QString &pluginPath=QString())
Means of accessing canonical single instance.
bool isEmpty() const
Returns true if the rectangle is empty.
virtual QString htmlMetadata()=0
Returns metadata in a format suitable for feeding directly into a subset of the GUI raster properties...
void setProviderType(const QString &providerType)
Sets the providerType (provider key)
virtual int capabilities() const
Returns a bitmask containing the supported capabilities.
QgsMapLayerRenderer * createMapRenderer(QgsRenderContext &rendererContext) override
Returns new instance of QgsMapLayerRenderer that will be used for rendering of given context.
void showStatusMessage(const QString &message)
QgsRasterDataProviderTemporalCapabilities * temporalCapabilities() override
Returns the provider's temporal capabilities.
QgsMapLayerType type() const
Returns the type of the layer.
void setMaxOversampling(double os)
void setPassword(const QString &password)
Sets the password for the URI.
QgsRectangle mDrawnExtent
Intersection of current map extent and layer extent.
virtual void setLayerOrder(const QStringList &layers)
Reorder the list of layer names to be rendered by this provider (in order from bottom to top)
QgsRasterMinMaxOrigin::Limits limits() const
Returns the raster limits.
void setLegend(QgsMapLayerLegend *legend)
Assign a legend controller to the map layer.
double width() const
Returns the width of the rectangle.
void setZoomedOutResampler(QgsRasterResampler *r)
Sets resampler for zoomed out scales. Takes ownership of the object.
QgsRasterDataProvider * dataProvider() override
Returns the source data provider.
QgsRasterLayer()
Constructor. Provider is not set.
virtual bool isValid() const =0
Returns true if this is a valid layer.
double cumulativeCutUpper() const
Returns the upper bound of cumulative cut method (between 0 and 1).
@ ContinuousPalette
Continuous palette, QGIS addition, GRASS.
double rasterUnitsPerPixelX() const
Returns the number of raster units per each raster pixel in X axis.
const QgsPathResolver & pathResolver() const
Returns path resolver for conversion between relative and absolute paths.
virtual QgsCoordinateReferenceSystem crs() const =0
Returns the coordinate system for the data source.
virtual QgsError error() const
Gets current status error.
@ IdentifyFormatUndefined
void readXml(const QDomElement &filterElem) override
Sets base class members from xml. Usually called from create() methods of subclasses.
@ Float64
Sixty four bit floating point (double)