Add cropTransparent to QgsImageOperation, for cropping transparent

borders from around an image
This commit is contained in:
vmora 2015-04-27 12:01:19 +10:00 committed by Nyall Dawson
parent 6a8526f91c
commit 0f35192f3f
3 changed files with 56 additions and 0 deletions

View File

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

View File

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

View File

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