Save array as a grayscale image.



  • Hello. I know the question like this has been asked many times on a number of forums, but no one proposed solution can help me. I want to clarify this question for good. How to convert an array of unsigned char to QImage and then save it in BMP format. Here is my code:

    QVector<QRgb> ctable;
    	for (int i = 0; i < 256; ++i)
    	{
    		ctable.push_back(qRgb(i, i, i));
    	}
                int  W=37; int H=37;
    	uchar  *data=new uchar[W*H];
    	for (int i = 0; i < H; i++)
    		for (int j = 0; j < W; j++)
    		{
    			data[i*W+j] = i;
    		}
    		QImage *tmp = new QImage(data, W, H,QImage::Format_Indexed8);
    		tmp->setColorTable(ctable);
    		tmp->save("1234.bmp");
    
    		delete tmp;
    		delete data;
    

    I want to get an image of 37x37, with gradient along Y. Really, I have some noise in last 3 rows as grayscale pixels. alt Here is
    Exploring filled data array with debugger shows thar all values are ok. I use MSVS 2013 and Qt 5.3.
    Could anyone, please, explain me where I'm wrong and correct my code? Thank you.



  • From the doc, the data array must be 32-bits aligned. I guess that's your problem: some data are lost because of the alignment.


Log in to reply
 

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