Reputation: 873
I have bytearray where every three bytes describes 1 pixel (RGB). The task is to convert it to jpeg or png. I receive the image palette from socket, construct its relevant RGB24 from the RGB table I have.
The problem I have is I cannot convert this bitmap to png now. for example:
image.loadFromData((const char*)bytes);
qDebug() << image.save("/home/saman/image.png");
if this is not the way, another option is adding png header to the bitmap array. However, I have no idea how to do that.
Anyone has any ideas please?
Upvotes: 2
Views: 3288
Reputation: 53215
You have several issues in these two lines:
Not specified save format for starter as per official documentation:.
QImage image; QByteArray ba; QBuffer buffer(&ba); buffer.open(QIODevice::WriteOnly); image.save(&buffer, "PNG"); // writes image into ba in PNG format
Not specified format for the loading.
You are doing C type cast in a C++ code.
You are doing the cast needlessly as there is a QByteArray overload.
You are casting to char*, whereas the expectation for that particular overload is unsigned char*.
You do not check the return value of the load operation.
QImage image; QByteArray ba; QBuffer buffer(&ba); buffer.open(QIODevice::WriteOnly); image.save(&buffer, "PNG"); // writes image into ba in PNG format
So, I would write something like this in your case:
if (!image.loadFromData((const char*)bytes, QImage::Format_RGB888))
qDebug() << "Could not load the image";
if (!image.save("/home/saman/image.png"), "PNG"))
qDebug() << "Could not save the image";
Naturally, you would also need to make sure the width and height are correct for the image because otherwise, the raw data is just sequential, and the class instance cannot really magically figure out.
Upvotes: 1
Reputation: 873
it seems I shoudav used the constructor to mention bytesPerLine used.
QImage *image =new QImage((const uchar*)bytes.constData(),600, 800,1800,QImage::Format_RGB888);
with bytes per line mentioned now everything works fine.
Upvotes: 1