Load QPixmap from QByteArray in Qt?
Asked Answered
C

3

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?

Claytonclaytonia answered 26/7, 2011 at 7:29 Comment(0)
P
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
}
Plastometer answered 26/7, 2011 at 7:32 Comment(4)
@raive : can you pls add a simple example ?Claytonclaytonia
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.Claytonclaytonia
Well, it depends from what you have in pdata. code is correct.Plastometer
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*Plastometer
R
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
    )
);
Rusty answered 26/7, 2011 at 7:45 Comment(1)
True, you can find the answer hereRusty
E
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.

Emissary answered 26/7, 2011 at 7:33 Comment(2)
i want to convert from byte array to Image ,but QImage takes first parameter as const uchar* not byte array )Claytonclaytonia
uchar is a byte. Just use a cast.Emissary

© 2022 - 2024 — McMap. All rights reserved.