How to display image from color data array in Qt?

I have char* datawhere each char represents a red / green / blue / alpha pixel value.

So, the first four digits are the red, green, blue and alpha values ​​of the first pixel, and the following four: R, G, B, the pixel value on the right, etc.

It represents an image (with previously known width and height).

Now I want to somehow take this array and display it in a Qt window. How to do it?

I know that I must somehow use QPixmap and / or QImage, but I can not find anything useful in the documentation.

+3
source share
1 answer

QImage ( ), - :

QImage DataToQImage( int width, int height, int length, char *data )
{
    QImage image( width, height, QImage::Format_ARGB32 );
    assert( length % 4 == 0 );
    for ( int i = 0; i < length / 4; ++i )
    {
        int index = i * 4;
        QRgb argb = qRgba( data[index + 1], //red
                           data[index + 2], //green
                           data[index + 3], //blue
                           data[index] );   //alpha
        image.setPixel( i, argb );
    }
    return image;
}

, :

QImage DataToQImage( int width, int height, int length, const uchar *data )
{
    int bytes_per_line = width * 4;
    QImage image( data, width, height, bytes_per_line, 
                     QImage::Format_ARGB32 );
    // data is required to be valid throughout the lifetime of the image so 
    // constructed, and QImages use shared data to make copying quick.  I 
    // don't know how those two features interact, so here I chose to force a 
    // copy of the image.  It could be that the shared data would make a copy
    // also, but due to the shared data, we don't really lose anything by 
    // forcing it.
    return image.copy();
}
+2

Source: https://habr.com/ru/post/1726939/


All Articles