QGIS API Documentation 3.99.0-Master (09f76ad7019)
Loading...
Searching...
No Matches
qgsalgorithmextractbinary.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmextractbinary.cpp
3 -----------------------------------
4 begin : November 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
20#include "qgsfeaturerequest.h"
21
22#include <QString>
23
24using namespace Qt::StringLiterals;
25
27
28QString QgsExtractBinaryFieldAlgorithm::name() const
29{
30 return u"extractbinary"_s;
31}
32
33QString QgsExtractBinaryFieldAlgorithm::displayName() const
34{
35 return QObject::tr( "Extract binary field" );
36}
37
38QString QgsExtractBinaryFieldAlgorithm::shortHelpString() const
39{
40 return QObject::tr( "This algorithm extracts contents from a binary field, saving them to individual files.\n\n"
41 "Filenames can be generated using values taken from "
42 "an attribute in the source table or based on a more complex expression." );
43}
44
45QString QgsExtractBinaryFieldAlgorithm::shortDescription() const
46{
47 return QObject::tr( "Extracts contents from a binary field, saving them to individual files." );
48}
49
50QStringList QgsExtractBinaryFieldAlgorithm::tags() const
51{
52 return QObject::tr( "blob,binaries,save,file,contents,field,column" ).split( ',' );
53}
54
55QString QgsExtractBinaryFieldAlgorithm::group() const
56{
57 return QObject::tr( "Vector table" );
58}
59
60QString QgsExtractBinaryFieldAlgorithm::groupId() const
61{
62 return u"vectortable"_s;
63}
64
65QgsExtractBinaryFieldAlgorithm *QgsExtractBinaryFieldAlgorithm::createInstance() const
66{
67 return new QgsExtractBinaryFieldAlgorithm();
68}
69
70void QgsExtractBinaryFieldAlgorithm::initAlgorithm( const QVariantMap & )
71{
72 addParameter( new QgsProcessingParameterFeatureSource( u"INPUT"_s, QObject::tr( "Input layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::Vector ) ) );
73
74 addParameter( new QgsProcessingParameterField( u"FIELD"_s, QObject::tr( "Binary field" ), QVariant(), u"INPUT"_s, Qgis::ProcessingFieldParameterDataType::Any ) );
75
76 addParameter( new QgsProcessingParameterExpression( u"FILENAME"_s, QObject::tr( "File name" ), QVariant(), u"INPUT"_s ) );
77
78 addParameter( new QgsProcessingParameterFolderDestination( u"FOLDER"_s, QObject::tr( "Destination folder" ) ) );
79}
80
81QVariantMap QgsExtractBinaryFieldAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
82{
83 std::unique_ptr<QgsProcessingFeatureSource> input( parameterAsSource( parameters, u"INPUT"_s, context ) );
84 if ( !input )
85 throw QgsProcessingException( invalidSourceError( parameters, u"INPUT"_s ) );
86
87 const QString fieldName = parameterAsString( parameters, u"FIELD"_s, context );
88 const int fieldIndex = input->fields().lookupField( fieldName );
89 if ( fieldIndex < 0 )
90 throw QgsProcessingException( QObject::tr( "Invalid binary field" ) );
91
92 const QString folder = parameterAsString( parameters, u"FOLDER"_s, context );
93 if ( !QDir().mkpath( folder ) )
94 throw QgsProcessingException( QObject::tr( "Failed to create output directory." ) );
95
96 const QDir dir( folder );
97 const QString filenameExpressionString = parameterAsString( parameters, u"FILENAME"_s, context );
98 QgsExpressionContext expressionContext = createExpressionContext( parameters, context, input.get() );
99
100 QSet<QString> fields;
101 fields.insert( fieldName );
102 QgsFeatureRequest request;
103
104 QgsExpression filenameExpression( filenameExpressionString );
105 filenameExpression.prepare( &expressionContext );
106 fields.unite( filenameExpression.referencedColumns() );
107 request.setSubsetOfAttributes( fields, input->fields() );
108 if ( !filenameExpression.needsGeometry() )
110
112 const double step = input->featureCount() > 0 ? 100.0 / input->featureCount() : 1;
113 int i = 0;
114 QgsFeature feat;
115 while ( features.nextFeature( feat ) )
116 {
117 i++;
118 if ( feedback->isCanceled() )
119 {
120 break;
121 }
122
123 feedback->setProgress( i * step );
124
125 const QByteArray ba = feat.attribute( fieldIndex ).toByteArray();
126 if ( ba.isEmpty() )
127 continue;
128
129 expressionContext.setFeature( feat );
130 const QString name = filenameExpression.evaluate( &expressionContext ).toString();
131 if ( filenameExpression.hasEvalError() )
132 {
133 feedback->reportError( QObject::tr( "Error evaluating filename: %1" ).arg( filenameExpression.evalErrorString() ) );
134 continue;
135 }
136
137 const QString path = dir.filePath( name );
138 QFile file( path );
139 if ( !file.open( QIODevice::WriteOnly | QFile::Truncate ) )
140 {
141 feedback->reportError( QObject::tr( "Could not open %1 for writing" ).arg( path ) );
142 }
143 else
144 {
145 file.write( ba );
146 file.close();
147 feedback->pushInfo( QObject::tr( "Extracted %1" ).arg( path ) );
148 }
149 }
150
151 QVariantMap outputs;
152 outputs.insert( u"FOLDER"_s, folder );
153 return outputs;
154}
155
156
@ Vector
Tables (i.e. vector layers with or without geometry). When used for a sink this indicates the sink ha...
Definition qgis.h:3610
@ NoGeometry
Geometry is not required. It may still be returned if e.g. required for a filter condition.
Definition qgis.h:2254
@ SkipGeometryValidityChecks
Invalid geometry checks should always be skipped. This flag can be useful for algorithms which always...
Definition qgis.h:3782
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the context.
Handles parsing and evaluation of expressions (formerly called "search strings").
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
Fetch next feature and stores in f, returns true on success.
Wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setFlags(Qgis::FeatureRequestFlags flags)
Sets flags that affect how features will be fetched.
QgsFeatureRequest & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:60
Q_INVOKABLE QVariant attribute(const QString &name) const
Lookup attribute value by attribute name.
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:55
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:63
Contains information about the context in which a processing algorithm is executed.
Custom exception class for processing related exceptions.
Base class for providing feedback from a processing algorithm.
virtual void pushInfo(const QString &info)
Pushes a general informational message from the algorithm.
virtual void reportError(const QString &error, bool fatalError=false)
Reports that the algorithm encountered an error while executing.
An expression parameter for processing algorithms.
An input feature source (such as vector layers) parameter for processing algorithms.
A vector layer or feature source field parameter for processing algorithms.
A folder destination parameter, for specifying the destination path for a folder created by the algor...