Trolltech Home | Qt-interest Home | Recent Threads | All Threads | Author | Date
All threads index page 1

Qt-interest Archive, November 2006
QColor::alpha()==255 always?


Message 1 in thread

I wrote some code intended to invert the pixels in a black and white image and 
set the alpha value for the previously white pixels to 0.  When I try to 
print out the pixel values using QColor::alpha() it shows the alpha value as 
255.  If, however, I print the raw numerical value for the pixel, it shows up 
(correctly) as 0.  Is this a bug or a feature?

#include <QtCore>
#include <QtGui>
#include <iostream>
void dumpImageInfo(const QImage& image){
  std::cout<<"h="<<image.height()<<" "<<"w="<<image.width()<<"\n"
	   <<"alpha="<<(image.hasAlphaChannel()?"true":"false")<<"\n";
    for(int x=0; x<image.width();++x){
      if(x)std::cout<<"\n";
      for(int y=0; y<image.height();++y){
	QColor color(image.pixel(x,y));
	std::cout<<(y?" ":"")<<color.alpha()<<":"<<image.pixel(x,y);
      }
    }
}

QImage invert(const QImage& src){
  QImage image(src.size(),QImage::Format_ARGB32);
  for(int x=0; x<image.width();++x)
    for(int y=0; y<image.height();++y)
      image.setPixel(x,y,
(qRed(src.pixel(x,y))?qRgba(0,0,0,0):qRgba(255,255,255,255)));
  return image;
}

int main(int argc, char* argv[]) {
  if(argc < 2){
    std::cerr<<"provide a file name"<<std::endl;
    return -1;
  }
  const QImage src(argv[1]);
  dumpImageInfo(invert(src));
  std::cout<<std::endl;
}
Here's an example of what is printed:
...
255:0 255:0 255:0 255:0 255:0 255:4294967295 255:4294967295 255:4294967295 
255:4294967295 255:4294967295 255:4294967295 255:4294967295 255:4294967295 
255:4294967295 255:4294967295 255:0 255:0 255:0 255:0 255:0 255:0 255:0 255:0
...

--
 [ signature omitted ] 

Message 2 in thread

Am Mittwoch, 1. November 2006 23:10 schrieb Steven T. Hatton:
> ...
>       if(x)std::cout<<"\n";
>       for(int y=0; y<image.height();++y){
> 	QColor color(image.pixel(x,y));
this initializes QColor with QRgb-value, i.e. QColor( QRgb )-ctor is called. 
That means, alpha always will be 255 (see docs). What you probably want is

...
const QRgb pix=image.pixel(x,y);
QColor color( qRed( pix ), qGreen( pix ), qBlue( pix ), qAlpha( pix ) );
...

This is quite slow code and could be faster by using char-pointers (returned 
by bits()/scanLine(...)) directly. and pass them indirected to QColor:


char * ptr = image.scanLine( x );
for(int y=0; y<image.height();++y){
QColor( *ptr, *(ptr+1), *(ptr+2), *(ptr+3)
ptr += 4
}

and so on...


toby

Attachment:

Attachment: pgpy33x3Z8XpA.pgp
Description: PGP signature