Search code examples
c++imageqtbufferqimage

Build a QImage from a buffer


How I can build a QImage from a buffer for example?
In this case I'm using a buffer of 3x3 with vale from 0 (black) to 255 (white).

0 255 0
255 0 255
0 255 0

and it is store into a unsigned char buffer[9] = {0, 255, 0, 255, 0, 255, 0, 255, 0};

At the moment I'm trying this but doesn't work:

QImage image{buffer, 3, 3, QImage::Format_Grayscale8};

Solution

  • The constructor you're using...

    QImage(uchar *data, int width, int height, QImage::Format format, QImageCleanupFunction cleanupFunction = nullptr, void *cleanupInfo = nullptr)
    

    has the caveat...

    data must be 32-bit aligned, and each scanline of data in the image must also be 32-bit aligned

    Hence the QImage implementation expects the number of bytes in each scanline to be a multiple of 4 -- a condition not satisfied by your data buffer. Instead make use of the constructor that allows you to specify the bytes-per-scanline explicitly...

    QImage(uchar *data, int width, int height, int bytesPerLine, QImage::Format format, QImageCleanupFunction cleanupFunction = nullptr, void *cleanupInfo = nullptr)
    

    So your code becomes...

    unsigned char buffer[9] = {0, 255, 0, 255, 0, 255, 0, 255, 0};
    QImage image{buffer, 3, 3, 3, QImage::Format_Grayscale8};