这篇文章主要介绍“怎么用QT实现视频传输功能”,在日常操作中,相信很多人在怎么用QT实现视频传输功能问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”怎么用QT实现视频传输功能”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
udp客户端,我们主要获取某个视频的文件,采用opencv读取后,分帧传输。我们将图片解码成base-64格式
参考代码
#include "ImageClient.h" #include<QDebug> #include<QBuffer> #include<QFileDialog> #include <opencv2/opencv.hpp> ImageClient::ImageClient(QWidget *parent) : QWidget(parent) { ui.setupUi(this); counter = 0; time = new QTimer(this); time->start(180); connect(time, SIGNAL(timeout()), this, SLOT(readFrame())); cap.open("F:/1.avi"); if (!cap.isOpened()) { qDebug() << " ===> Failed"; } else { qDebug() << " ===> Succeed"; } receiver = new QUdpSocket(this); } QByteArray ImageClient::getImageData2( QImage &image) { QByteArray imageData; QBuffer buffer(&imageData); image.save(&buffer, "jpg"); imageData = imageData.toBase64(); return imageData; } QImage ImageClient::mat2QImage(cv::Mat cvImg) { QImage qImg; if (cvImg.channels() == 3) //3 channels color image { cv::cvtColor(cvImg, cvImg, COLOR_BGR2RGB); qImg = QImage((const unsigned char*)(cvImg.data), cvImg.cols, cvImg.rows, cvImg.cols*cvImg.channels(), QImage::Format_RGB888); } else if (cvImg.channels() == 1) //grayscale image { qImg = QImage((const unsigned char*)(cvImg.data), cvImg.cols, cvImg.rows, cvImg.cols*cvImg.channels(), QImage::Format_Indexed8); } else { qImg = QImage((const unsigned char*)(cvImg.data), cvImg.cols, cvImg.rows, cvImg.cols*cvImg.channels(), QImage::Format_RGB888); } return qImg; } void ImageClient::readFrame() { counter++; Mat source, result; qDebug() << counter; cap.read(source); if (source.empty())//如果视频已经读取完成则停止发送timeout()信号 { time->stop(); qDebug() << "End"; return; } auto image = mat2QImage(source) ; ui.label->setPixmap(QPixmap::fromImage(image)); auto data = getImageData2(image); receiver->writeDatagram(data.data(), data.size(), QHostAddress::Broadcast, //udp广播地址 7777); }
获取客户端数据然后展现。代码如下:
#include "Server.h" #include<QMutexLocker> #pragma execution_character_set("utf-8") Server::Server(QWidget *parent) : QWidget(parent) { ui.setupUi(this); udpSocket = new QUdpSocket(this); udpSocket->bind(QHostAddress::AnyIPv4, 7777); connect(udpSocket, SIGNAL(readyRead()), this, SLOT(Run()), Qt::QueuedConnection);//udp数据接收 } QImage Server::getImage(const QString &data) { QByteArray imageData = QByteArray::fromBase64(data.toLatin1()); QImage image; image.loadFromData(imageData); return image; } void Server::Run() { try { QMutexLocker locker(&mutexImage); datagram.resize(udpSocket->pendingDatagramSize()); auto len = udpSocket->readDatagram(datagram.data(), datagram.size()); auto image = Server::getImage(datagram); ui.label->setPixmap(QPixmap::fromImage(image)); this_thread::sleep_for(std::chrono::milliseconds(180)); } catch (const std::exception& e) { } }
到此,关于“怎么用QT实现视频传输功能”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。