【问题标题】:how to display image from array of colors data in Qt?如何在 Qt 中显示颜色数据数组中的图像?
【发布时间】:2023-04-10 19:21:01
【问题描述】:

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

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

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

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

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

【问题讨论】:

    标签: qt


    【解决方案1】:

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

    【讨论】:

    • 使用 QRgb rgba = qRgba(r,g,b,a) 代替手动移位。但我更喜欢第二种解决方案。
    • @TimW:谢谢,我编辑了示例以使用该功能,但我完全忘记了。 (不过,我确实尝试找到 QRgb 构造函数......)
    猜你喜欢
    • 2021-11-12
    • 2018-01-20
    • 1970-01-01
    • 2017-03-14
    • 2018-07-15
    • 2020-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多