Qt中使用UDP的方式传送图片

1.首先将图片转换成QByteArray

QPixmap pixmap = QPixmap::fromImage(image);
QByteArray bytes;
QBuffer buff(&bytes);
buff.open(QIODevice::ReadWrite);
pixmap.save(&buff, "JPG");

2.定义数据包包头结构体

struct ImageFrameHead {
    unsigned int funCode;               //功能码,用于区分数据包中的内容
    unsigned int uTransFrameHdrSize;    //sizeof(ImageFrameHead),数据包头的大小
    unsigned int uTransFrameSize;       //Data Size,数据包中数据的大小
    //数据帧变量
    unsigned int uDataFrameSize;        //图片数据总大小
    unsigned int uDataFrameTotal;       //图片数据被分数据帧个数
    unsigned int uDataFrameCurr;        //数据帧当前的帧号
    unsigned int uDataInFrameOffset;    //数据帧在整帧的偏移
};

3.划分图片数据,按照每帧1024个字节划分

#define DATA_FRAME_SIZE 1024
QByteArray sendBuff;
sendBuff.resize(DATA_FRAME_SIZE);
int size = buff.size();
int num = 0;
int count = 0;
int endSize = size%(DATA_FRAME_SIZE - sizeof(ImageFrameHead));
if (endSize == 0)
{
    num = size/(DATA_FRAME_SIZE - sizeof(ImageFrameHead));
}
else
{
    num = size/(DATA_FRAME_SIZE - sizeof(ImageFrameHead)) + 1;
}
while (count < num)
{
    memset(sendBuff.data(), 0, 1024);
    ImageFrameHead head;
    head.funCode = XchatVideo;
    head.uTransFrameHdrSize = sizeof(ImageFrameHead);
    if ((count+1) != num) {
        head.uTransFrameSize = DATA_FRAME_SIZE - sizeof(ImageFrameHead);
    }
    else {
        head.uTransFrameSize = endSize;
    }
    head.uDataFrameSize = size;
    head.uDataFrameTotal = num;
    head.uDataFrameCurr = count+1;
    head.uDataInFrameOffset = count*(DATA_FRAME_SIZE - sizeof(ImageFrameHead));
    memcpy(sendBuff.data()+sizeof(ImageFrameHead), (bytes.data()+head.uDataInFrameOffset), DATA_FRAME_SIZE - sizeof(ImageFrameHead));
    memcpy(sendBuff.data(), (char *)&head, sizeof(ImageFrameHead));
    //使用udp将sendbuff发送到指定地址
    sendData(sendBuff);
    count++;
}

4.接收端接收到符合条件的数据后,将数据拼包,直到组成完整数据之后,将数据转换成QImage.

QByteArray recvBuf;
char* m_buf = new char[1024*1024];
while(m_udpSocket->hasPendingDatagrams())
{
    int size = m_udpSocket->pendingDatagramSize();
    recvBuf.resize(size);
    m_udpSocket->readDatagram(recvBuf.data(), size);
    unsigned int head = 0;
    memcpy(&head, recvBuf.data(), sizeof(unsigned int));
    if(head == XchatVideo)
    {
        ImageFrameHead *imgHead = (ImageFrameHead *)recvBuf.data();
        memcpy(m_buf + (imgHead->uDataInFrameOffset), (recvBuf.data()+ sizeof(ImageFrameHead)), imgHead->uTransFrameSize);
        if (imgHead->uDataFrameCurr == imgHead->uDataFrameTotal)
        {
            QByteArray data;
            data.resize(imgHead->uDataFrameSize);
            memcpy(data.data(), m_buf, imgHead->uDataFrameSize);
            QImage image;
            image.loadFromData(data,"JPG");
            QPixmap pixmap = QPixmap::fromImage(image);
        }
    }
}
delete m_buf;


展开阅读全文

没有更多推荐了,返回首页