Create a QByteArray from a QImage and vice-versa
我需要将已经创建的QImage编码为QByteArray以发送到套接字,并在另一端对其进行解码。
在服务器端,我正在尝试执行以下操作:
1 2 3 4 5 6 7 8 9 10 11 | // The vector is mandatory. The class that creates the image line expects it. QVector<unsigned char> msg; QImage line(create_image_line(msg)); QByteArray ba((char*)line.bits(), line.numBytes()); for (int i = 0; i < ba.size(); ++i) { msg.append(ba[i]); } send_msg(msg); |
create_image_line的功能类似于:
1 2 3 4 | ... handle the msg and get the image properties... QImage img(pixels_, 1, QImage::Format_RGB32); ... set the values ... return(img); |
在客户端:
1 2 3 4 5 6 7 8 | receive_msg(msg); QByteArray ba; for (int i = 0; i < msg.size(); ++i) { ba.append(msg[i]); } QImage line(LINE_WIDTH, 1, QImage::Format_RGB32); line.fromData(ba); |
出问题了,并且图像显示出很多噪点(我知道问题出在此转换中,这是另一个成功的测试所致)。
我想知道问题出在哪里。
Rgds。
因此,按照现在的方式进行操作,您需要循环遍历line.bits并再次复制像素。
但是,QDataStream可以序列化大多数Qt值类型,包括QImage。 如果您可以控制两端并愿意更改协议,那么这可能是一个更简单且更可靠的解决方案。