[Solved] Need help saving a 24-bit image to file



  • I'm trying to figure out how to save out an 8-bit per channel RGB image file. The problem is that the resulting file doesn't look correct.

    Below is my example code. I'm creating a pixel array and setting all channels to 0 so I'm expecting a black image. However, the generated BMP has some weird colored pixels near the end and I don't know why. "Link to BMP":http://1drv.ms/1yubTkT

    @int len = 9;
    int size = len * len * 3;
    unsigned char* pixelData = new unsigned char[size];
    for( int i=0; i<size; i+=3 ){
    pixelData[i] = 0;
    pixelData[i+1] = 0;
    pixelData[i+2] = 0;
    }
    QImage image( pixelData, len, len, QImage::Format_RGB888);
    image.save( "C:/work/test.bmp" );
    delete [] pixelData;@

    If I modify the code so it writes out RGBA, I do not have a problem and the resulting file looks correct. Here's the modified code:
    @int len = 9;
    int size = len * len * 4;
    unsigned char* pixelData = new unsigned char[size];
    for( int i=0; i<size; i+=4 ){
    pixelData[i] = 0;
    pixelData[i+1] = 0;
    pixelData[i+2] = 0;
    pixelData[i+3] = 255;
    }
    QImage image( pixelData, len, len, QImage::Format_ARGB32);
    image.save( "C:/work/test.png" );
    delete [] pixelData;@

    What am I missing when writing out the RGB file?
    Thanks.


  • Moderators

    From the docs of QImage constructor:
    "The width and height must be specified in pixels, data must be 32-bit aligned, and each scanline of data in the image must also be 32-bit aligned."

    So even if you use RGB888 format as the internal structure of the image the input needs to be RGBA.



  • Here is how I got it to work. Format_RGB888 was not behaving as I expected. It seemed to use the alpha value when writing out the color. For example, given [0, 0, 0, 255, 0, 0, 0, 255, 0, ...], it would first get the first three elements (0,0,0) and write out black. It would then get the next three elements (255, 0, 0) and write out red. I did get it to work if I changed the format to Format_RGB32.

    @
    int len = 9;
    int size = len * len * 4;
    unsigned char* pixelData = new unsigned char[size];
    for( int i=0; i<size; i+=4 ){
    pixelData[i] = 0;
    pixelData[i+1] = 0;
    pixelData[i+2] = 0;
    pixelData[i+3] = 255;
    }
    QImage image( pixelData, len, len, QImage::Format_RGB32);
    image.save( "C:/work/test.bmp" );
    delete [] pixelData;
    @


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.