convert QPixmap to QImage without loosing alphaChannel



  • Hi,

    i have a QPixmap that has an alpha channel.
    now i want to change some pixels and therefore convert it into a QImage

    QImage image(pixmap.toImage().convertToFormat(QImage::Format_ARGB32));
    

    When i now iterate over the pixels, the alpha value is always 255.
    How can i prevent loosing the alpha channel?


  • Moderators

    @gde23 "Usually this will be QImage::Format_ARGB32_Premultiplied for pixmaps with an alpha" from http://doc.qt.io/qt-5/qpixmap.html#toImage
    Maybe you should try QImage::Format_ARGB32_Premultiplied ?



  • @jsulm I have tried

    QImage image(pixmap.toImage().convertToFormat(QImage::Format_ARGB32_Premultiplied));
    

    However still the same problem.
    I think also the order does not make sense since first it is converted to image (I guess here the alpha gets lost) and then afterwards it is converted to different format?


  • Moderators

    @gde23 Try

    QImage image = pixmap.toImage();
    


  • @jsulm still the same result.

    or maybe the problem is with convertig to QColor?
    Here is the complete function.

    void grayOut(QPixmap& pixmap)
    {
        QImage image = pixmap.toImage();
        for(int x=0; x<image.width(); x++)
        {
            for(int y=0; y<image.height(); y++)
            {
                QColor colour(image.pixel(x,y));
                int m = colour.red() + colour.green()+colour.blue();
                int alpha = colour.alpha();
                m/=3;
                colour.setRgb(m, m, m, alpha);
                image.setPixel(x, y, colour.rgba());
            } 
        }
        pixmap = QPixmap::fromImage(image);
    }
    

    all i am trying todo is to gray out the icon, however

    int alpha = colour.alpha();
    

    always returns 255


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.