2009-12-30 313 views
3

我有一個char* data,其中每個字符表示一個像素的紅/綠/藍/ alpha值。如何從Qt中的顏色數據數組顯示圖像?

所以,前四個數字分別是紅色,綠色,藍色和alpha值的第一個像素,接下來的四個是R,G,B,右邊像素的A值等等。

它代表一張圖片(以前已知的寬度和高度)。

現在,我想以某種方式採取這個數組,並顯示在Qt窗口。怎麼做?

我知道我應該以某種方式使用QPixmap和/或QImage,但我找不到有用的文檔。

回答

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

而不是手動換檔使用QRgb rgba = qRgba(r,g,b,a)。但我更喜歡第二種解決方案。 – TimW 2009-12-31 08:00:57

+0

@TimW:謝謝,我編輯了這個例子來使用那個我完全忘記的函數。 (雖然我嘗試查找QRgb構造函數,但是...) – 2009-12-31 14:26:58