13

I am trying to create QByteArray from QImage, however although I tried lots of varient, I couldn't handle it.

What I am doing is :

QImage img_enrll; // <--- There is an image coming from another function. 

QByteArray arr((char*)img_enrll.bits(),img_enrll.byteCount());  // <-- convertion but I am not sure it is true or not. 

funcCheck((unsigned char*)arr.data(), arr.size(), 0, &sam, 1, &n);


virtual Error funcCheck (const uint8_t    src[],
                           size_t           src_len,
                           size_t           tout_ms,
                           IRawSample*      dst[],
                           size_t           dst_len,
                           size_t*          dst_n )

However Error code is return Invalid Data. I think that converting QImage to QByteArray is wrong. Please could you kindly help me how to convert to QByteArray?

László Papp
  • 51,870
  • 39
  • 111
  • 135
goGud
  • 4,163
  • 11
  • 39
  • 63

3 Answers3

13

You could do this:

QImage img_enrll;
QByteArray arr;
QBuffer buffer(&arr);
buffer.open(QIODevice::WriteOnly);
img_enrll.save(&buffer, "yourformat");

Having written that, if you need this for serialization, you are better of with QDataStream.

Adam
  • 488
  • 4
  • 17
László Papp
  • 51,870
  • 39
  • 111
  • 135
  • Ohh, thank you, I also tried this solution before. But QDataStream gives me good idea how to solve this problem. And also it works fine :) – goGud Dec 07 '14 at 14:43
  • 1
    Hmmm, I've seen this solution in Qt documentation, but buffer remains empty in my case. Namely, `Q_ASSERT(buffer.data().size() > 0);` throws an exception. Of course, I've checked that the QImage is valid: I've loaded it from file, converted to QPixmap and displayed it inside QLabel. – Alexandr Zarubkin Jan 26 '17 at 13:15
6

Try this:

QByteArray arr = QByteArray::fromRawData((const char*)img.bits(), img.byteCount());
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Tarek.Mh
  • 638
  • 10
  • 8
0

In my case I needed a deep copy, so what worked was:

QByteArray arr(img.byteCount(), Qt::Uninitialized) // or resize if it already exists
memcpy(arr.data(), img.constBits(), img.byteCount());
Adriel Jr
  • 2,451
  • 19
  • 25