Qt:QCamera打开系统摄像头,截图保存实例

时间:2022-12-09 15:59:36

​​                  

Qt,C++ 学习交流群: 302558294(欢迎你的加入)

效果图:

Qt:QCamera打开系统摄像头,截图保存实例


动态图太大,这里我就不弄动态图了。


用到三个库:

#include <QCamera>
#include <QCameraImageCapture>
#include <QCameraViewfinder>


注意:

在.pro文件中添加

QT += multimedia
QT += multimediawidgets



源码:

main.cpp

#include <QApplication>
#include <QCameraImageCapture>
#include "mainwindow.h"

int main(int argc, char *argv[])
{
QApplication a(argc, argv);

MainWindow w;
w.show();

return a.exec();
}


mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QCamera>
#include <QCameraImageCapture>
#include <QCameraViewfinder>
#include "ui_mainwindow.h"

class MainWindow : public QMainWindow ,public Ui_MainWindow
{
Q_OBJECT

public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void onSavePicture();

private:
QCamera *mCamera;
QCameraImageCapture *mCameraImageCapture;
QVideoWidget *widget;
};

#endif // MAINWINDOW_H


mainwindow.cpp

#include <QWidget>
#include <QVideoWidget>
#include <QFileDialog>
#include <QDir>
#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
{
setupUi(this);
connect(saveBtn,SIGNAL(clicked(bool)),SLOT(onSavePicture()));

mCamera = new QCamera;//启用系统摄像头
mCameraImageCapture = new QCameraImageCapture(mCamera);//用摄像头初始化一个QCameraImageCapture用来截图
mCameraImageCapture->setCaptureDestination(QCameraImageCapture::CaptureToFile);
mCamera->setCaptureMode(QCamera::CaptureStillImage);//设置摄像头的模式,可以抓取静态图像
mCamera->setViewfinder(viewfinder);//设置显示的窗体
mCamera->start();//摄像头启动
}

MainWindow::~MainWindow()
{

}

void MainWindow::onSavePicture()
{
QString fileName = QFileDialog::getSaveFileName(this, QString::fromLocal8Bit("保存图片"),
QDir::currentPath(),
tr("Images (*.png *.xpm *.jpg)"));
mCameraImageCapture->capture(fileName);
}