I am trying to capture images continuously so I can send them using UDP. I am doing this to implement a live video streaming program.
The code below captures images continuously and assigns images to QGraphicsScene so I can test if images play like a video. But when I run the program my computer freezes after couple seconds even though I delete the pointers. How can I fix this problem ?
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QThread>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
scene = new QGraphicsScene(this);
ui->graphicsView->setScene(scene);
cam = new QCamera;
cam->setCaptureMode(QCamera::CaptureStillImage);
viewfinder = new QCameraViewfinder;
viewfinder->show();
QCameraImageCapture *cap = new QCameraImageCapture(cam);
cap->setCaptureDestination(QCameraImageCapture::CaptureToBuffer);
cam->setViewfinder(viewfinder);
QObject::connect(cap, &QCameraImageCapture::imageCaptured, [=] (int id, QImage img) {
while(true){
QByteArray *buf = new QByteArray;
QBuffer *buffer=new QBuffer(buf);
buffer->open(QIODevice::WriteOnly);
img.save(buffer, "BMP");
QPixmap *pixmap = new QPixmap();
pixmap->loadFromData(buffer->buffer());
scene->addPixmap(*pixmap);
delete buf;
delete buffer;
delete pixmap;
QThread::sleep(0.0416);
cap->capture();
}
});
QObject::connect(cap, &QCameraImageCapture::readyForCaptureChanged, [=] (bool state) {
if(state == true) {
cam->searchAndLock();
cap->capture();
cam->unlock();
}
});
cam->start();
}
MainWindow::~MainWindow()
{
delete ui;
}
Your implementation of your goal to "... capture images continuously to send them ..." via the slow QCameraImageCapture in a loop calls for trouble (lagging, UI blocking).
Better use the following subclass.