11

I have a byte array with the contents of an image (in png/bmp or some other format).

How can I load it into a QPixmap?

sashoalm
  • 75,001
  • 122
  • 434
  • 781
Bokambo
  • 4,204
  • 27
  • 79
  • 130

3 Answers3

19
bool QPixmap::loadFromData ( const QByteArray & data, const char * format = 0, Qt::ImageConversionFlags flags = Qt::AutoColor )

Format here is string literal like "PNG" or something similar

QPixmap p;
QByteArray pData;
// fill array with image
if(p.loadFromData(pData,"PNG"))
{
   // do something with pixmap
}
Raiv
  • 5,731
  • 1
  • 33
  • 51
  • @raive : can you pls add a simple example ? – Bokambo Jul 26 '11 at 07:40
  • BYTE* pData; QByteArray pArray; pArray.append((const char*) pData); m_pixmap.loadFromData(pArray,"PNG"); m_pixmap.save((QString("./Test.png"), "PNG")); I am using this code but it seems to be not working. – Bokambo Jul 28 '11 at 04:32
  • Well, it depends from what you have in pdata. code is correct. – Raiv Jul 28 '11 at 07:28
  • I saw two other your questions - about QByteArray and about the non-gui thread... trouble is probably there. And answers you received are correct - use QImage and provide size for your data loaded from byte* – Raiv Jul 28 '11 at 07:41
7

You should use the folowing, where your bytes are in the imageData variable in the format specified by the last parameter:

QPixmap pixmap = QPixmap::fromImage(
    QImage(
        (unsigned char *) imageData, 
        image_width, 
        image_height, 
        QImage::Format_RGB888
    )
);
Matyas
  • 13,473
  • 3
  • 60
  • 73
  • True, you can find the answer [here](http://stackoverflow.com/questions/6854290/it-is-not-safe-to-use-pixmaps-outside-the-gui-thread-in-qt-embedded-linux) – Matyas Jul 28 '11 at 11:41
0

Use this constructor:

QImage ( const uchar * data, int width, int height, Format format )

Here is more info. After that, you can use QPixmap.convertFromImage() to create a pixmap.

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820