Skip to content
Permalink
Browse files

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 0f35192f3fbdeb0b615890efc1410ed6f7fabe74
@@ -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() );

};
@@ -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;
@@ -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

0 comments on commit 0f35192

Please sign in to comment.
You can’t perform that action at this time.