qt 使用QCamera 实现简单的摄像头使用

qt 自带的摄像头QCamera可简单实现摄像头监控,话不多说,直接上代码!自己写的测试代码!







源码:

pro文件

#-------------------------------------------------

#
# Project created by QtCreator 2017-12-08T14:36:05
#
#-------------------------------------------------
 
 
QT       += core gui
QT       += multimedia
QT       += multimediawidgets
 
 
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
 
 
TARGET = QCameraTest
TEMPLATE = app
 
 
 
 
SOURCES += main.cpp\
        widget.cpp
 
 
HEADERS  += widget.h
 
 

.h文件

#ifndef WIDGET_H

#define WIDGET_H
 
 
#include <QWidget>
 
 
class QCamera;
class QCameraViewfinder;
class QCameraImageCapture;
class Widget : public QWidget
{
    Q_OBJECT
 
 
public:
    Widget(QWidget *parent = 0);
    ~Widget();
 
 
private slots:
    void exitBtnResponded();
    void cameraImageCaptured(int,QImage);
 
 
private:
    QCamera*             m_pCamera;       //读取摄像头
    QCameraViewfinder*   m_pViewfinder;   //渲染摄像头
    QCameraImageCapture* m_pImageCapture; //获取摄像头当前帧
};
 
 
#endif // WIDGET_H
 
 

.cpp文件

#include "widget.h"

#include <QLayout>
#include <QLabel>
#include <QPushButton>
#include <QFileDialog>
 
 
#include <QCamera>
#include <QCameraViewfinder>
#include <QCameraImageCapture>
 
 
Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    setWindowTitle("QCamera");
 
 
    m_pCamera = new QCamera(this);
    m_pViewfinder = new QCameraViewfinder(this);
    m_pImageCapture = new QCameraImageCapture(m_pCamera);
 
 
    QPushButton* button1 = new QPushButton("Capture");
    QPushButton* button2 = new QPushButton("Exit");
 
 
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->addWidget(m_pViewfinder);
    mainLayout->addWidget(button1);
    mainLayout->addWidget(button2);
 
 
    connect(button1, SIGNAL(clicked()), m_pImageCapture, SLOT(capture()));
    connect(button2, SIGNAL(clicked()), this, SLOT(exitBtnResponded()));
    connect(m_pImageCapture, SIGNAL(imageCaptured(int,QImage)), this, SLOT(cameraImageCaptured(int,QImage)));
 
 
    m_pImageCapture->setCaptureDestination(QCameraImageCapture::CaptureToFile);
    m_pCamera->setCaptureMode(QCamera::CaptureStillImage);
    m_pCamera->setViewfinder(m_pViewfinder);
    m_pCamera->start();
}
 
 
Widget::~Widget()
{
    delete       m_pCamera;
    delete   m_pViewfinder;
    delete m_pImageCapture;
}
 
 
void Widget::exitBtnResponded()
{
    m_pCamera->stop();
    close();
}
 
 
void Widget::cameraImageCaptured(int, QImage image)
{
    QString savepath = QFileDialog::getSaveFileName(this,"Save Capture","Capture","Image png(*.png);;Image jpg(*.jpg);;Image bmp(*.bmp)");
    if(!savepath.isEmpty()){
        image.save(savepath);
    }
}
 
 


完整项目下载地址:http://download.csdn.net/download/u012532263/10151298

猜你喜欢

转载自blog.csdn.net/u012532263/article/details/78753276