如何在Qt中显示颜色数据数组的图像?

时间:2009-12-30 22:30:07

标签: qt

我有一个char* data,其中每个字符代表一个像素的红色/绿色/蓝色/ alpha值。

所以,前四个数字是第一个像素的红色,绿色,蓝色和alpha值,接下来的四个是R,G,B,右边像素的A值,依此类推。

它代表一张图片(以前已知的宽度和高度)。

现在,我想以某种方式获取此数组并将其显示在Qt窗口上。怎么做?

我知道我应该以某种方式使用QPixmap和/或QImage,但我在文档中找不到任何有用的东西。

1 个答案:

答案 0 :(得分:2)

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;
}

基于遇到another constructor,您可能也可以这样做:

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();
}