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.
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());
Solved the problem using this:
memcpy(data,bytes.constData(),bytes.size()+1);
Should have tried that at least.
Not directly related, but is there any reason you use libcurl instead of the integrated QNetworkAccessManager?
you may use strdup()
. This method is doing this
char *strdup (const char *s) {
char *d = malloc (strlen (s) + 1); // Space for length plus nul
if (d == NULL) return NULL; // No memory
strcpy (d,s); // Copy the characters
return d; // Return the new string
}
more info here: strdup() - what does it do in C?
so that you get a char*
, whereas ConstData()
will return a const char*
精彩评论