Create QImage from an unsigned char array
-
Hi,
I would like to print a picture from an unsigned char array. I tried to use QImage but I don't think I use it properly, the GUI always shows me a grey picture.
Here is my sample code :
int main(int argc, char *argv[]) { QApplication a(argc, argv); QLabel l; QImage i; unsigned char* data = (unsigned char*) malloc (1024*768*sizeof(unsigned char)); for (int i = 0; i < 1024; i++) { for (int j = 0; j < 768; j++) { data[768 * i + j] = 255; } } free(data); i = QImage(data, 768, 1024, QImage::Format_Indexed8); l.setPixmap(QPixmap::fromImage(i)); l.show(); return a.exec(); }
How would you do to get a correct picture ? Thanks for your help !
-
@Vick said:
I tried to use QImage but I don't think I use it properly, the GUI always shows me a grey picture.
You just fill the data with the value 255?! If i would have to guess it seems like it's grey, because you monitor needs some calibration maybe. I would expect it to be white.
Also you mixed the height and width in this line.
i = QImage(data, 768, 1024, QImage::Format_Indexed8);
But it's not noticeable yet, since the data is all filled with the same value.
-
hi
You might need a ColorTable?void MainWindow::paintEvent(QPaintEvent* e) { uchar imagio [500][500]; for (int i = 0; i < 500; i++) for (int j = 0; j < 500; j++) imagio[i][j] = qrand() % 256; QVector<QRgb> colorTable; for (int i = 0; i < 256; i++) colorTable.push_back(QColor(qrand() % 256, qrand() % 256, qrand() % 256).rgb()); QImage image((uchar*)imagio, 500, 500, 500, QImage::Format_Indexed8); image.setColorTable(colorTable); QPainter p(this); p.drawImage(QPoint(0, 0), image); }
-
If you just want grayscale you can also use Format_Grayscale8 instead of Format_Indexed8.
...
Just to expand my comment, like the other two said you need a color table for indexed format. Format_Grayscale8 would take care of that in this case and display the respective gray values. -
@Vick said:
Yes, but I tried other values like 0, i and it does not change anything... Always getting this grey picture !
because @mrjj is correct.
The image format QImage::Format_Indexed8 needs a color map.
The way you want to use it is specifying the color for each pixel, so you need to use for example QImage::Format_ARGB32_Premultiplied. -
@Vick You free the memory with your image data before you pass it to QImage. Why?
unsigned char* data = (unsigned char*) malloc (1024*768*sizeof(unsigned char)); for (int i = 0; i < 1024; i++) { for (int j = 0; j < 768; j++) { data[768 * i + j] = 255; } } // Here you free the memory free(data); i = QImage(data, 768, 1024, QImage::Format_Indexed8);
In C++ you should not use malloc/free. Use new/delete[] instead. And in this case there is no need to allocate the memory on the heap.