简体   繁体   中英

Save QImage to array of bytes

I need to open an image and store it bytes into normal array. Only for opening and getting byte data i can use Qt, for everything else I need to use plain c++. Problem is that I don't know how to do it. Already I know about that:

QImage image;
QByteArray ba;
QBuffer buffer(&ba);
buffer.open(QIODevice::WriteOnly);
image.save(&buffer, "PNG"); // writes image into ba in PNG format

But to be honest I don't understand what it does. What I plan to do is opening image, store it data to QByteArray and then write it data to normal array.

Can someone help me understand how to do it ?

I'm not sure whether you are asking "how" to do it or trying to understand what is actually going on in this piece of code. I'm guessing it's the latter, therefore I will try to explain it.

You have a QImage , then you have a QByteArray .

Then you create a QBuffer which gets the byte array you've created earlier as a parameter, open s it in Write-Only mode (because you will write the bytes into the array).

QImage has a function save which gets a buffer and a format (not mandatory). Then converts the image into the byte array. That's the main trick here, and what got you confused here I guess.

Note: I would personally prefer to open the image file as a QFile and read it into raw bytes with readAll() .

QFile* imageFile = new QFile("image.png");
imageFile->open(QIODevice::ReadOnly);
QByteArray ba = imageFile->readAll();
imageFile->close();
delete imageFile;

After that you can even access its raw data by calling ba.data() .

I hope that helps.

You can read more about QImage::save function here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM