PDA

View Full Version : How it create a true alpha mask from a QImage?



nokkie
3rd May 2010, 19:18
Hello, I've been trying to create a simple alpha mask from a QImage using CreateAlphaMask but for some reason I can't get the mask to work correctly. I only want the simplest mask possible, if there is any alpha at all then set the bit for that pixel in the alpha mask to be 1.

My problem with QImage::CreateAlphaMask is that no matter what Qt::ImageConversionFlags I try to use, it seems to not detect pixels with only a slight alpha.

Here's a list of the flags I've tried already:



Image.createAlphaMask(); // Qt::AutoColor | Qt::DiffuseDither
Image.createAlphaMask( Qt::ThresholdAlphaDither );
Image.createAlphaMask( Qt::DiffuseAlphaDither );
Image.createAlphaMask( Qt::AvoidDither );
Image.createAlphaMask( Qt::NoOpaqueDetection );


Is Qt designed to do what I want to do? or should I loop through the pixels myself and find the true alpha mask? It seems what I need is to use "Qt::ThresholdAlphaDither" but be able to set the threshhold to 0.

nokkie
3rd May 2010, 22:07
I just wrote my own, if anyone knows how to have qt do this internally or a better way to do this let me know, here's the code in case anyone else is having the same problem:



QImage CreateAlphaMask( const QImage& srcImage )
{
// QImage one only creates alpha mask for alpha values greater than 128... need it to be all alpha greater than 0

int nWidth = m_PatchSetImage.width();
int nHeight = m_PatchSetImage.height();
int nDepth = m_PatchSetImage.depth();

QImage alphaMask( nWidth, nHeight, QImage::Format_MonoLSB );
alphaMask.setColor( 0, 0xffffffff );
alphaMask.setColor( 1, 0xff000000 );

// initialize everything to 0 first
memset( alphaMask.bits(), 0, alphaMask.numBytes() );

switch ( nDepth )
{
case 32:
for ( int y = 0; y < nHeight; ++y )
{
unsigned char* pMaskData = alphaMask.scanLine( y );
unsigned int* pSrcData = (unsigned int*)srcImage.scanLine( y );

for ( int x = 0; x < nWidth; ++x )
{
if ( *pSrcData++ >> 24 )
{
pMaskData[x/8] |= 1 << (x % 8);
}
}
}
break;
default:
// Set mask to all 1's if not 32 bit depth
memset( alphaMask.bits(), 0xFF, alphaMask.numBytes() );
break;
}

return alphaMask;
}