Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Add cropTransparent to QgsImageOperation, for cropping transparent
borders from around an image
  • Loading branch information
vmora authored and nyalldawson committed Apr 27, 2015
1 parent 6a8526f commit 0f35192
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 0 deletions.
9 changes: 9 additions & 0 deletions python/core/effects/qgsimageoperation.sip
Expand Up @@ -131,4 +131,13 @@ class QgsImageOperation
*/
static void flipImage( QImage &image, FlipType type );

/** Crop any transparent border from around an image.
* @param image source image
* @param minSize minimum size for cropped image, if desired. If the
* cropped image is smaller than the minimum size, it will be centered
* in the returned image.
* @note added in QGIS 2.9
*/
static QImage cropTransparent( const QImage & image, const QSize& minSize = QSize() );

};
38 changes: 38 additions & 0 deletions src/core/effects/qgsimageoperation.cpp
Expand Up @@ -793,6 +793,44 @@ void QgsImageOperation::flipImage( QImage &image, QgsImageOperation::FlipType ty
runLineOperation( image, flipOperation );
}

QImage QgsImageOperation::cropTransparent( const QImage &image, const QSize &minSize )
{
int width = image.width();
int height = image.height();
int xmin = width;
int xmax = 0;
int ymin = height;
int ymax = 0;

for ( int x = 0; x < width; ++x )
{
for ( int y = 0; y < height; ++y )
{
if ( qAlpha( image.pixel( x, y ) ) )
{
xmin = qMin( x, xmin );
xmax = qMax( x, xmax );
ymin = qMin( y, ymin );
ymax = qMax( y, ymax );
}
}
}
if ( minSize.isValid() )
{
if ( xmax - xmin < minSize.width() ) // centers image on x
{
xmin = qMax(( xmax + xmin ) / 2 - minSize.width() / 2, 0 );
xmax = xmin + minSize.width();
}
if ( ymax - ymin < minSize.height() ) // centers image on y
{
ymin = qMax(( ymax + ymin ) / 2 - minSize.height() / 2, 0 );
ymax = ymin + minSize.height();
}
}
return image.copy( xmin, ymin, xmax - xmin, ymax - ymin );
}

void QgsImageOperation::FlipLineOperation::operator()( QRgb *startRef, const int lineLength, const int bytesPerLine )
{
int increment = ( mDirection == QgsImageOperation::ByRow ) ? 4 : bytesPerLine;
Expand Down
9 changes: 9 additions & 0 deletions src/core/effects/qgsimageoperation.h
Expand Up @@ -162,6 +162,15 @@ class CORE_EXPORT QgsImageOperation
*/
static void flipImage( QImage &image, FlipType type );

/** Crop any transparent border from around an image.
* @param image source image
* @param minSize minimum size for cropped image, if desired. If the
* cropped image is smaller than the minimum size, it will be centered
* in the returned image.
* @note added in QGIS 2.9
*/
static QImage cropTransparent( const QImage & image, const QSize& minSize = QSize() );

private:

//for blocked operations
Expand Down

0 comments on commit 0f35192

Please sign in to comment.