PDA

View Full Version : setting QPixmap's alpha channel



ugluk
17th September 2012, 08:42
Does there exist a better way to do it than this?



void setAlphaChannel(QPixmap& pixmap, int const alpha)
{
QImage image(pixmap.toImage().convertToFormat(QImage::For mat_ARGB32));

for (int x(0); x != image.width(); ++x)
{
for (int y(0); y != image.height(); ++y)
{
QColor color(image.pixel(x,y));

color.setAlpha(alpha);

image.setPixel(x, y, color.rgba());
}
}

pixmap = QPixmap::fromImage(image);
}

I've read about the now-obsolete QPixmap method called setAlphaChannel(), but it's implementations are platform-dependent.

ChrisW67
17th September 2012, 10:42
These are fairly equal (350ms over 1000 conversions) on my machine:


QPixmap input("Lenna.png");

QImage image(input.size(), QImage::Format_ARGB32_Premultiplied);
image.fill(Qt::transparent);
QPainter p(&image);
p.setOpacity(0.2);
p.drawPixmap(0, 0, input);
p.end();

QPixmap output = QPixmap::fromImage(image);

// or

QPixmap output(input.size());
outut.fill(Qt::transparent);
QPainter p(&output);
p.setOpacity(0.2);
p.drawPixmap(0, 0, input);
p.end();

Your code comes in at around 8850 ms for the same 1000 conversions.

ugluk
17th September 2012, 16:07
Did you try method #1 without the fill? Perhaps this would work?



QImage image(pixmap.size(), QImage::Format_ARGB32_Premultiplied);

{
QPainter painter(&image);

painter.setCompositionMode(QPainter::CompositionMo de_Source);

painter.setOpacity(.2);
painter.drawPixmap(0, 0, pixmap);
}

pixmap = QPixmap::fromImage(image);

ChrisW67
17th September 2012, 23:51
I did the pixmap version first: without the fill I was not getting an alpha channel in the PNG I saved from the pixmap version. I just left it in the image version, but it seems to work fine without and is faster still.

ugluk
18th September 2012, 09:08
I've found an example by Nokia, it is even more complicated :)

http://www.developer.nokia.com/Community/Wiki/Archived:Transparent_QPixmap_picture

What puzzles me is the fill(Qt::transparent). Why is the fill() needed, if the entire transparent QPixmap or QImage is filled and the CompositionMode is QPainter::CompositionMode_Source?