一个简单的demo,使用电脑内置摄像头,拍照,并在当前目录保存截图,效果图。
一添加media模块
![](https://i-blog.csdnimg.cn/blog_migrate/1a2a9e18ee8fc1fdf81306ce347a639c.jpeg)
使用camer需要使用3个类
QCamera类用于打开系统的摄像头设备
QCameraViewfinder用于显示捕获的视频
QCameraImageCapture用于截图
#include <QCamera>
#include <QCameraViewfinder>
#include <QCameraImageCapture>
二 QCameraImageCapture
QCameraImageCapture创建实例后需要指定使用那个camera,
QCameraImageCapture的capture()方法用于截图,同时会发送QCameraImageCapture::imageCaptured的信号,可以编写槽函数捕获。参数(int,qimage)
QCameraImageCapture::setCaptureDestination()方法用于设置捕获为文件或者缓冲区,默认为文件。
eeee,没啥难点,直接上代码
代码
camera.h
#pragma once
#include <QtWidgets/QWidget>
#include "ui_Camera.h"
#include<qcamera.h>
#include <QCameraViewfinder>
#include <QCameraImageCapture>
#include <QVBoxLayout>
#include<qpushbutton.h>
class Camera : public QWidget
{
Q_OBJECT
public:
Camera(QWidget *parent = Q_NULLPTR);
private:
Ui::CameraClass ui;
QCamera *m_camera;
QCameraViewfinder *m_cameraViewFinder;
QCameraImageCapture *m_ImageCapture;
QHBoxLayout *m_layout;
QPushButton *m_button;
void OnGatherClicked();
void OnimageCaptured(int , QImage);
};
Camera.cpp
#include "Camera.h"
Camera::Camera(QWidget *parent)
: QWidget(parent)
{
m_camera = new QCamera();
m_cameraViewFinder = new QCameraViewfinder();//用于显示捕获的视频
m_ImageCapture = new QCameraImageCapture(m_camera);//用于截图
connect(m_ImageCapture, &QCameraImageCapture::imageCaptured, this,&Camera::OnimageCaptured);
m_button = new QPushButton(this);
m_button->setText(QString::fromLocal8Bit("截图保存"));
//m_button->show();
connect(m_button, &QPushButton::clicked, this, &Camera::OnGatherClicked);
m_layout = new QHBoxLayout();
m_layout->addWidget(m_cameraViewFinder);
m_layout->addWidget(m_button);
m_ImageCapture->setCaptureDestination(QCameraImageCapture::CaptureToFile);
m_camera->setViewfinder(m_cameraViewFinder);
m_camera->start();
this->setGeometry(500,500,1100,700);
this->setLayout(m_layout);
}
void Camera::OnGatherClicked()
{
m_ImageCapture->capture();
}
void Camera::OnimageCaptured(int id, QImage image)
{
qDebug() << id << endl;
image.save("./BUF.jpg", "JPG", 100);
}