tags:

views:

114

answers:

3

I'm having trouble with saving a QPixmap to QByteArray, then writing it to char*. For example i'm trying to write to a file with ofstream.

                 QByteArray bytes;
                 QBuffer buff(&bytes);
                 buff.open(QIODevice::ReadOnly);
                 pixmap.save(&buff, "PNG");

                 QString str(bytes);

                 char *data;
                 data =  (char*)qstrdup(str.toAscii().constData());

                ofstream myfile;
                 myfile.open ("test.jpg");
                   myfile << data;
                   myfile.close();

But all i get in that file is:

‰PNG

The reason i need a char* , is because i'm having some permission problems when writing to disk, then sending with libcurl. I want to load it to a char* , then send it directly from memory.

+2  A: 

You encounter a null-byte. You'll need something like write(), because the << operator doesn't allow you to tell how long the string is and stops writing at the first null byte:

const QByteArray array = str.toAscii();
myfile.write(array.constData(), array.size());

See e.g. http://www.cplusplus.com/reference/iostream/ostream/write/

Ivo
I think this is very likely the problem but the OP may also want to use buff.open(QIODevice::WriteOnly) since they are writing to the buffer and just in case pixmap.save() doesn't close it, follow it with buff.close().
Arnold Spence
yes,that works thank you, but im writing to a file, just to see if i can get the QByteArray to char*.Thing im asking for is, how do i get that array to char*.i tried strcpy(data,array.constData()); but it doesnt work.
Biber
strcpy also depends on the null-byte, try memcopy(data, array.constData(), array.size()).
Ivo
oh, you beat me to it. thank you very much. :)
Biber
A: 

Solved the problem using this:

 memcpy(data,bytes.constData(),bytes.size()+1);

Should have tried that at least.

Biber
The +1 isn't strictly necessary, because `bytes.constData()` is exactly `bytes.size()` long.
Ivo
oh, thank you again.
Biber
A: 

Not directly related, but is there any reason you use libcurl instead of the integrated QNetworkAccessManager?

guruz
never tried it, im kind of used to libcurl.but i guess i will give it a try once.
Biber