原理很简单。 QCamera用于捕获当前设备上的相机。 QCameraImageCapture用于捕获每一帧图片。 当QCameraImageCapture发送imageCaptured信号的时候。这个时候我们自定义一个槽函数来获取一帧图片 当然还需要定义一个定时器,用于主动触发捕获图片。 直接看代码: .h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
class QCamera;
class QCameraViewfinder;
class QCameraImageCapture;
class QLabel;
class QTimer;
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
protected slots:
void onCaptureClicked();
void onExitClicked();
void onImageCaptured(int id, const QImage &preview);
void update();
private:
QCamera *m_pCamera=nullptr;
QCameraViewfinder* m_pViewfinder=nullptr;
QCameraImageCapture* m_pImageCapture=nullptr;
QLabel *m_pShowLabel=nullptr;
QImage m_Image;
QTimer *m_pTimer=nullptr;
};
#endif
.cpp
#include "widget.h"
#include <QPushButton>
#include <QCamera>
#include <QCameraViewfinder>
#include <QCameraImageCapture>
#include <QVBoxLayout>
#include <QLabel>
#include <QTimer>
#include <QMessageBox>
#include <QSettings>
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
m_pCamera=new QCamera(this);
m_pViewfinder = new QCameraViewfinder(this);
m_pShowLabel=new QLabel(this);
m_pImageCapture = new QCameraImageCapture(m_pCamera);
QPushButton* button1 = new QPushButton("Capture");
QPushButton* button2 = new QPushButton("Exit");
button1->setFixedSize(100,25);
button2->setFixedSize(100,25);
QVBoxLayout *mainLayout=new QVBoxLayout(this);
mainLayout->addWidget(button1);
mainLayout->addWidget(button2);
mainLayout->addWidget(m_pShowLabel);
connect(button1,&QPushButton::clicked,this,&Widget::onCaptureClicked);
connect(button2,&QPushButton::clicked,this,&Widget::onExitClicked);
connect(m_pImageCapture,&QCameraImageCapture::imageCaptured,this,&Widget::onImageCaptured);
m_pImageCapture->setCaptureDestination(QCameraImageCapture::CaptureToFile);
m_pCamera->setCaptureMode(QCamera::CaptureVideo);
m_pCamera->start();
m_pTimer = new QTimer(this);
connect(m_pTimer, SIGNAL(timeout()), this, SLOT(update()));
this->resize(800,600);
}
Widget::~Widget()
{
}
void Widget::onCaptureClicked()
{
m_pTimer->start(100);
}
void Widget::onExitClicked()
{
m_pTimer->stop();
}
void Widget::onImageCaptured(int id, const QImage &preview)
{
m_Image=preview.convertToFormat(QImage::Format_RGB888);
m_pShowLabel->setPixmap(QPixmap::fromImage(m_Image));
}
void Widget::update()
{
m_pImageCapture->capture();
}
效果图:
|