QGIS API Documentation  3.20.0-Odense (decaadbb31)
qgsalgorithmimportphotos.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgsalgorithmimportphotos.cpp
3  ------------------
4  begin : March 2018
5  copyright : (C) 2018 by Nyall Dawson
6  email : nyall dot dawson at gmail dot com
7  ***************************************************************************/
8 
9 /***************************************************************************
10  * *
11  * This program is free software; you can redistribute it and/or modify *
12  * it under the terms of the GNU General Public License as published by *
13  * the Free Software Foundation; either version 2 of the License, or *
14  * (at your option) any later version. *
15  * *
16  ***************************************************************************/
17 
19 #include "qgsogrutils.h"
20 #include "qgsvectorlayer.h"
21 #include <QDirIterator>
22 #include <QFileInfo>
23 #include <QRegularExpression>
24 
26 
27 QString QgsImportPhotosAlgorithm::name() const
28 {
29  return QStringLiteral( "importphotos" );
30 }
31 
32 QString QgsImportPhotosAlgorithm::displayName() const
33 {
34  return QObject::tr( "Import geotagged photos" );
35 }
36 
37 QStringList QgsImportPhotosAlgorithm::tags() const
38 {
39  return QObject::tr( "exif,metadata,gps,jpeg,jpg" ).split( ',' );
40 }
41 
42 QString QgsImportPhotosAlgorithm::group() const
43 {
44  return QObject::tr( "Vector creation" );
45 }
46 
47 QString QgsImportPhotosAlgorithm::groupId() const
48 {
49  return QStringLiteral( "vectorcreation" );
50 }
51 
52 void QgsImportPhotosAlgorithm::initAlgorithm( const QVariantMap & )
53 {
54  addParameter( new QgsProcessingParameterFile( QStringLiteral( "FOLDER" ), QObject::tr( "Input folder" ), QgsProcessingParameterFile::Folder ) );
55  addParameter( new QgsProcessingParameterBoolean( QStringLiteral( "RECURSIVE" ), QObject::tr( "Scan recursively" ), false ) );
56 
57  std::unique_ptr< QgsProcessingParameterFeatureSink > output = std::make_unique< QgsProcessingParameterFeatureSink >( QStringLiteral( "OUTPUT" ), QObject::tr( "Photos" ), QgsProcessing::TypeVectorPoint, QVariant(), true );
58  output->setCreateByDefault( true );
59  addParameter( output.release() );
60 
61  std::unique_ptr< QgsProcessingParameterFeatureSink > invalid = std::make_unique< QgsProcessingParameterFeatureSink >( QStringLiteral( "INVALID" ), QObject::tr( "Invalid photos table" ), QgsProcessing::TypeVector, QVariant(), true );
62  invalid->setCreateByDefault( false );
63  addParameter( invalid.release() );
64 }
65 
66 QString QgsImportPhotosAlgorithm::shortHelpString() const
67 {
68  return QObject::tr( "Creates a point layer corresponding to the geotagged locations from JPEG images from a source folder. Optionally the folder can be recursively scanned.\n\n"
69  "The point layer will contain a single PointZ feature per input file from which the geotags could be read. Any altitude information from the geotags will be used "
70  "to set the point's Z value.\n\n"
71  "Optionally, a table of unreadable or non-geotagged photos can also be created." );
72 }
73 
74 QgsImportPhotosAlgorithm *QgsImportPhotosAlgorithm::createInstance() const
75 {
76  return new QgsImportPhotosAlgorithm();
77 }
78 
79 QVariant QgsImportPhotosAlgorithm::parseMetadataValue( const QString &value )
80 {
81  QRegularExpression numRx( QStringLiteral( "^\\s*\\(\\s*([-\\.\\d]+)\\s*\\)\\s*$" ) );
82  QRegularExpressionMatch numMatch = numRx.match( value );
83  if ( numMatch.hasMatch() )
84  {
85  return numMatch.captured( 1 ).toDouble();
86  }
87  return value;
88 }
89 
90 bool QgsImportPhotosAlgorithm::extractGeoTagFromMetadata( const QVariantMap &metadata, QgsPointXY &tag )
91 {
92  double x = 0.0;
93  if ( metadata.contains( QStringLiteral( "EXIF_GPSLongitude" ) ) )
94  {
95  bool ok = false;
96  x = metadata.value( QStringLiteral( "EXIF_GPSLongitude" ) ).toDouble( &ok );
97  if ( !ok )
98  return false;
99 
100  if ( metadata.value( QStringLiteral( "EXIF_GPSLongitudeRef" ) ).toString().rightRef( 1 ).compare( QLatin1String( "W" ), Qt::CaseInsensitive ) == 0
101  || metadata.value( QStringLiteral( "EXIF_GPSLongitudeRef" ) ).toDouble() < 0 )
102  x = -x;
103  }
104  else
105  {
106  return false;
107  }
108 
109  double y = 0.0;
110  if ( metadata.contains( QStringLiteral( "EXIF_GPSLatitude" ) ) )
111  {
112  bool ok = false;
113  y = metadata.value( QStringLiteral( "EXIF_GPSLatitude" ) ).toDouble( &ok );
114  if ( !ok )
115  return false;
116 
117  if ( metadata.value( QStringLiteral( "EXIF_GPSLatitudeRef" ) ).toString().rightRef( 1 ).compare( QLatin1String( "S" ), Qt::CaseInsensitive ) == 0
118  || metadata.value( QStringLiteral( "EXIF_GPSLatitudeRef" ) ).toDouble() < 0 )
119  y = -y;
120  }
121  else
122  {
123  return false;
124  }
125 
126  tag = QgsPointXY( x, y );
127  return true;
128 }
129 
130 QVariant QgsImportPhotosAlgorithm::extractAltitudeFromMetadata( const QVariantMap &metadata )
131 {
132  QVariant altitude;
133  if ( metadata.contains( QStringLiteral( "EXIF_GPSAltitude" ) ) )
134  {
135  double alt = metadata.value( QStringLiteral( "EXIF_GPSAltitude" ) ).toDouble();
136  if ( metadata.contains( QStringLiteral( "EXIF_GPSAltitudeRef" ) ) &&
137  ( ( metadata.value( QStringLiteral( "EXIF_GPSAltitudeRef" ) ).type() == QVariant::String && metadata.value( QStringLiteral( "EXIF_GPSAltitudeRef" ) ).toString().right( 1 ) == QLatin1String( "1" ) )
138  || metadata.value( QStringLiteral( "EXIF_GPSAltitudeRef" ) ).toDouble() < 0 ) )
139  alt = -alt;
140  altitude = alt;
141  }
142  return altitude;
143 }
144 
145 QVariant QgsImportPhotosAlgorithm::extractDirectionFromMetadata( const QVariantMap &metadata )
146 {
147  QVariant direction;
148  if ( metadata.contains( QStringLiteral( "EXIF_GPSImgDirection" ) ) )
149  {
150  direction = metadata.value( QStringLiteral( "EXIF_GPSImgDirection" ) ).toDouble();
151  }
152  return direction;
153 }
154 
155 QVariant QgsImportPhotosAlgorithm::extractOrientationFromMetadata( const QVariantMap &metadata )
156 {
157  QVariant orientation;
158  if ( metadata.contains( QStringLiteral( "EXIF_Orientation" ) ) )
159  {
160  switch ( metadata.value( QStringLiteral( "EXIF_Orientation" ) ).toInt() )
161  {
162  case 1:
163  orientation = 0;
164  break;
165  case 2:
166  orientation = 0;
167  break;
168  case 3:
169  orientation = 180;
170  break;
171  case 4:
172  orientation = 180;
173  break;
174  case 5:
175  orientation = 90;
176  break;
177  case 6:
178  orientation = 90;
179  break;
180  case 7:
181  orientation = 270;
182  break;
183  case 8:
184  orientation = 270;
185  break;
186  }
187  }
188  return orientation;
189 }
190 
191 QVariant QgsImportPhotosAlgorithm::extractTimestampFromMetadata( const QVariantMap &metadata )
192 {
193  QVariant ts;
194  if ( metadata.contains( QStringLiteral( "EXIF_DateTimeOriginal" ) ) )
195  {
196  ts = metadata.value( QStringLiteral( "EXIF_DateTimeOriginal" ) );
197  }
198  else if ( metadata.contains( QStringLiteral( "EXIF_DateTimeDigitized" ) ) )
199  {
200  ts = metadata.value( QStringLiteral( "EXIF_DateTimeDigitized" ) );
201  }
202  else if ( metadata.contains( QStringLiteral( "EXIF_DateTime" ) ) )
203  {
204  ts = metadata.value( QStringLiteral( "EXIF_DateTime" ) );
205  }
206 
207  if ( !ts.isValid() )
208  return ts;
209 
210  QRegularExpression dsRegEx( QStringLiteral( "(\\d+):(\\d+):(\\d+)\\s+(\\d+):(\\d+):(\\d+)" ) );
211  QRegularExpressionMatch dsMatch = dsRegEx.match( ts.toString() );
212  if ( dsMatch.hasMatch() )
213  {
214  int year = dsMatch.captured( 1 ).toInt();
215  int month = dsMatch.captured( 2 ).toInt();
216  int day = dsMatch.captured( 3 ).toInt();
217  int hour = dsMatch.captured( 4 ).toInt();
218  int min = dsMatch.captured( 5 ).toInt();
219  int sec = dsMatch.captured( 6 ).toInt();
220  return QDateTime( QDate( year, month, day ), QTime( hour, min, sec ) );
221  }
222  else
223  {
224  return QVariant();
225  }
226 }
227 
228 QVariant QgsImportPhotosAlgorithm::parseCoord( const QString &string )
229 {
230  QRegularExpression coordRx( QStringLiteral( "^\\s*\\(\\s*([-\\.\\d]+)\\s*\\)\\s*\\(\\s*([-\\.\\d]+)\\s*\\)\\s*\\(\\s*([-\\.\\d]+)\\s*\\)\\s*$" ) );
231  QRegularExpressionMatch coordMatch = coordRx.match( string );
232  if ( coordMatch.hasMatch() )
233  {
234  double hours = coordMatch.captured( 1 ).toDouble();
235  double minutes = coordMatch.captured( 2 ).toDouble();
236  double seconds = coordMatch.captured( 3 ).toDouble();
237  return hours + minutes / 60.0 + seconds / 3600.0;
238  }
239  else
240  {
241  return QVariant();
242  }
243 }
244 
245 QVariantMap QgsImportPhotosAlgorithm::parseMetadataList( const QStringList &input )
246 {
247  QVariantMap results;
248  QRegularExpression splitRx( QStringLiteral( "(.*?)=(.*)" ) );
249  for ( const QString &item : input )
250  {
251  QRegularExpressionMatch match = splitRx.match( item );
252  if ( !match.hasMatch() )
253  continue;
254 
255  QString tag = match.captured( 1 );
256  QVariant value = parseMetadataValue( match.captured( 2 ) );
257 
258  if ( tag == QLatin1String( "EXIF_GPSLatitude" ) || tag == QLatin1String( "EXIF_GPSLongitude" ) )
259  value = parseCoord( value.toString() );
260  results.insert( tag, value );
261  }
262  return results;
263 }
264 
265 
266 class SetEditorWidgetForPhotoAttributePostProcessor : public QgsProcessingLayerPostProcessorInterface
267 {
268  public:
269 
271  {
272  if ( QgsVectorLayer *vl = qobject_cast< QgsVectorLayer * >( layer ) )
273  {
274  QVariantMap config;
275  // photo field shows picture viewer
276  config.insert( QStringLiteral( "DocumentViewer" ), 1 );
277  config.insert( QStringLiteral( "FileWidget" ), true );
278  config.insert( QStringLiteral( "UseLink" ), true );
279  config.insert( QStringLiteral( "FullUrl" ), true );
280  vl->setEditorWidgetSetup( vl->fields().lookupField( QStringLiteral( "photo" ) ), QgsEditorWidgetSetup( QStringLiteral( "ExternalResource" ), config ) );
281 
282  config.clear();
283  // path field is a directory link
284  config.insert( QStringLiteral( "FileWidgetButton" ), true );
285  config.insert( QStringLiteral( "StorageMode" ), 1 );
286  config.insert( QStringLiteral( "UseLink" ), true );
287  config.insert( QStringLiteral( "FullUrl" ), true );
288  vl->setEditorWidgetSetup( vl->fields().lookupField( QStringLiteral( "directory" ) ), QgsEditorWidgetSetup( QStringLiteral( "ExternalResource" ), config ) );
289  }
290  }
291 };
292 
293 QVariantMap QgsImportPhotosAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
294 {
295  QString folder = parameterAsFile( parameters, QStringLiteral( "FOLDER" ), context );
296 
297  QDir importDir( folder );
298  if ( !importDir.exists() )
299  {
300  throw QgsProcessingException( QObject::tr( "Directory %1 does not exist!" ).arg( folder ) );
301  }
302 
303  bool recurse = parameterAsBoolean( parameters, QStringLiteral( "RECURSIVE" ), context );
304 
305  QgsFields outFields;
306  outFields.append( QgsField( QStringLiteral( "photo" ), QVariant::String ) );
307  outFields.append( QgsField( QStringLiteral( "filename" ), QVariant::String ) );
308  outFields.append( QgsField( QStringLiteral( "directory" ), QVariant::String ) );
309  outFields.append( QgsField( QStringLiteral( "altitude" ), QVariant::Double ) );
310  outFields.append( QgsField( QStringLiteral( "direction" ), QVariant::Double ) );
311  outFields.append( QgsField( QStringLiteral( "rotation" ), QVariant::Int ) );
312  outFields.append( QgsField( QStringLiteral( "longitude" ), QVariant::String ) );
313  outFields.append( QgsField( QStringLiteral( "latitude" ), QVariant::String ) );
314  outFields.append( QgsField( QStringLiteral( "timestamp" ), QVariant::DateTime ) );
315  QString outputDest;
316  std::unique_ptr< QgsFeatureSink > outputSink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, outputDest, outFields,
317  QgsWkbTypes::PointZ, QgsCoordinateReferenceSystem( QStringLiteral( "EPSG:4326" ) ) ) );
318 
319  QgsFields invalidFields;
320  invalidFields.append( QgsField( QStringLiteral( "photo" ), QVariant::String ) );
321  invalidFields.append( QgsField( QStringLiteral( "filename" ), QVariant::String ) );
322  invalidFields.append( QgsField( QStringLiteral( "directory" ), QVariant::String ) );
323  invalidFields.append( QgsField( QStringLiteral( "readable" ), QVariant::Bool ) );
324  QString invalidDest;
325  std::unique_ptr< QgsFeatureSink > invalidSink( parameterAsSink( parameters, QStringLiteral( "INVALID" ), context, invalidDest, invalidFields ) );
326 
327  QStringList nameFilters { "*.jpeg", "*.jpg" };
328  QStringList files;
329 
330  if ( !recurse )
331  {
332  QFileInfoList fileInfoList = importDir.entryInfoList( nameFilters, QDir::NoDotAndDotDot | QDir::Files );
333  for ( auto infoIt = fileInfoList.constBegin(); infoIt != fileInfoList.constEnd(); ++infoIt )
334  {
335  files.append( infoIt->absoluteFilePath() );
336  }
337  }
338  else
339  {
340  QDirIterator it( folder, nameFilters, QDir::NoDotAndDotDot | QDir::Files, QDirIterator::Subdirectories );
341  while ( it.hasNext() )
342  {
343  it.next();
344  files.append( it.filePath() );
345  }
346  }
347 
348  auto saveInvalidFile = [&invalidSink]( QgsAttributes & attributes, bool readable )
349  {
350  if ( invalidSink )
351  {
352  QgsFeature f;
353  attributes.append( readable );
354  f.setAttributes( attributes );
355  invalidSink->addFeature( f, QgsFeatureSink::FastInsert );
356  }
357  };
358 
359  double step = files.count() > 0 ? 100.0 / files.count() : 1;
360  int i = 0;
361  for ( const QString &file : files )
362  {
363  i++;
364  if ( feedback->isCanceled() )
365  {
366  break;
367  }
368 
369  feedback->setProgress( i * step );
370 
371  QFileInfo fi( file );
372  QgsAttributes attributes;
373  attributes << QDir::toNativeSeparators( file )
374  << fi.completeBaseName()
375  << QDir::toNativeSeparators( fi.absolutePath() );
376 
377  gdal::dataset_unique_ptr hDS( GDALOpen( file.toUtf8().constData(), GA_ReadOnly ) );
378  if ( !hDS )
379  {
380  feedback->reportError( QObject::tr( "Could not open %1" ).arg( QDir::toNativeSeparators( file ) ) );
381  saveInvalidFile( attributes, false );
382  continue;
383  }
384 
385  if ( char **GDALmetadata = GDALGetMetadata( hDS.get(), nullptr ) )
386  {
387  if ( !outputSink )
388  continue;
389 
390  QgsFeature f;
391  QVariantMap metadata = parseMetadataList( QgsOgrUtils::cStringListToQStringList( GDALmetadata ) );
392 
393  QgsPointXY tag;
394  if ( !extractGeoTagFromMetadata( metadata, tag ) )
395  {
396  // no geotag
397  feedback->reportError( QObject::tr( "Could not retrieve geotag for %1" ).arg( QDir::toNativeSeparators( file ) ) );
398  saveInvalidFile( attributes, true );
399  continue;
400  }
401 
402  QVariant altitude = extractAltitudeFromMetadata( metadata );
403  QgsGeometry p = QgsGeometry( new QgsPoint( tag.x(), tag.y(), altitude.toDouble(), 0, QgsWkbTypes::PointZ ) );
404  f.setGeometry( p );
405 
406  attributes
407  << altitude
408  << extractDirectionFromMetadata( metadata )
409  << extractOrientationFromMetadata( metadata )
410  << tag.x()
411  << tag.y()
412  << extractTimestampFromMetadata( metadata );
413  f.setAttributes( attributes );
414  outputSink->addFeature( f, QgsFeatureSink::FastInsert );
415  }
416  else
417  {
418  feedback->reportError( QObject::tr( "No metadata found in %1" ).arg( QDir::toNativeSeparators( file ) ) );
419  saveInvalidFile( attributes, true );
420  }
421  }
422 
423  QVariantMap outputs;
424  if ( outputSink )
425  {
426  outputs.insert( QStringLiteral( "OUTPUT" ), outputDest );
427 
428  if ( context.willLoadLayerOnCompletion( outputDest ) )
429  {
430  context.layerToLoadOnCompletionDetails( outputDest ).setPostProcessor( new SetEditorWidgetForPhotoAttributePostProcessor() );
431  }
432  }
433 
434  if ( invalidSink )
435  outputs.insert( QStringLiteral( "INVALID" ), invalidDest );
436  return outputs;
437 }
438 
A vector of attributes.
Definition: qgsattributes.h:58
This class represents a coordinate reference system (CRS).
Holder for the widget type and its configuration for a field.
@ FastInsert
Use faster inserts, at the cost of updating the passed features to reflect changes made at the provid...
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition: qgsfeature.h:56
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
Definition: qgsfeature.cpp:135
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
Definition: qgsfeature.cpp:145
bool isCanceled() const SIP_HOLDGIL
Tells whether the operation has been canceled already.
Definition: qgsfeedback.h:54
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition: qgsfeedback.h:63
Encapsulate a field in an attribute table or data source.
Definition: qgsfield.h:51
Container of fields for a vector layer.
Definition: qgsfields.h:45
bool append(const QgsField &field, FieldOrigin origin=OriginProvider, int originIndex=-1)
Appends a field. The field must have unique name, otherwise it is rejected (returns false)
Definition: qgsfields.cpp:59
A geometry is the spatial representation of a feature.
Definition: qgsgeometry.h:124
Base class for all map layer types.
Definition: qgsmaplayer.h:70
static QStringList cStringListToQStringList(char **stringList)
Converts a c string list to a QStringList.
A class to represent a 2D point.
Definition: qgspointxy.h:59
double y
Definition: qgspointxy.h:63
Q_GADGET double x
Definition: qgspointxy.h:62
Point geometry type, with support for z-dimension and m-values.
Definition: qgspoint.h:49
void setPostProcessor(QgsProcessingLayerPostProcessorInterface *processor)
Sets the layer post-processor.
Contains information about the context in which a processing algorithm is executed.
bool willLoadLayerOnCompletion(const QString &layer) const
Returns true if the given layer (by ID or datasource) will be loaded into the current project upon co...
QgsProcessingContext::LayerDetails & layerToLoadOnCompletionDetails(const QString &layer)
Returns a reference to the details for a given layer which is loaded on completion of the algorithm o...
Custom exception class for processing related exceptions.
Definition: qgsexception.h:83
Base class for providing feedback from a processing algorithm.
virtual void reportError(const QString &error, bool fatalError=false)
Reports that the algorithm encountered an error while executing.
An interface for layer post-processing handlers for execution following a processing algorithm operat...
virtual void postProcessLayer(QgsMapLayer *layer, QgsProcessingContext &context, QgsProcessingFeedback *feedback)=0
Post-processes the specified layer, following successful execution of a processing algorithm.
A boolean parameter for processing algorithms.
An input file or folder parameter for processing algorithms.
@ TypeVector
Tables (i.e. vector layers with or without geometry). When used for a sink this indicates the sink ha...
Definition: qgsprocessing.h:54
@ TypeVectorPoint
Vector point layers.
Definition: qgsprocessing.h:49
Represents a vector layer which manages a vector based data sets.
std::unique_ptr< std::remove_pointer< GDALDatasetH >::type, GDALDatasetCloser > dataset_unique_ptr
Scoped GDAL dataset.
Definition: qgsogrutils.h:136