QT调用摄像头

本文详细介绍如何在Qt中利用多媒体模块实现摄像头的初始化、显示实时画面、拍照及保存图片功能。通过具体代码示例,讲解了如何在.pro文件中添加必要的模块,创建并配置QCamera、QCameraViewfinder和QCameraImageCapture对象,以及如何触发拍照和保存图片的动作。

步骤:
1.在.pro文件下添加两个模块。如下:

QT += multimedia    #这个模块包含<QCamera><QCameraImageCapture>
QT += multimediawidgets  #包含<QCameraViewfinder>
  1. widget.h头文件,如下:
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>

#include <QCamera>//系统摄像设备(摄像头)
#include <QCameraViewfinder>//摄像取景器部件
#include <QCameraImageCapture>//截图部件
#include <QFileDialog> //保存时候打开文件窗口

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

private slots:
	//定义槽函数
    void captureImage();
    void displayImage(int,QImage);
    void saveImage();

private:
    Ui::Widget *ui;

    QCamera *camera;
    QCameraViewfinder *viewfinder;
    QCameraImageCapture *imageCapture;
};

#endif // WIDGET_H

  1. widget.cpp文件,如下:
#include "widget.h"
#include "ui_widget.h"
#include <QPen>
#include <QPainter>
#include <QDebug>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
        ui->setupUi(this);

        //申请空间
        camera=new QCamera(this); //系统摄像设备(摄像头)
        viewfinder=new QCameraViewfinder(this);//摄像取景器部件
        imageCapture=new QCameraImageCapture(camera); //截图部件  指定父对象camera 依赖摄像头截图

        camera->setViewfinder(viewfinder);//申请好的取景部件给摄像头
        camera->start();//运行摄像头

        //注意:
        //ImageView是 horizontalLayout 类的对象
        //ImageCapture是Lable 类的对象
        ui->ImageView ->addWidget(viewfinder);//摄像头取到的景放入ImageView
        ui->ImageCapture->setScaledContents(true); //让图片适应ImageCapture的大小

        //horizontalLayout 类有捕捉图像的功能
        connect(imageCapture, SIGNAL(imageCaptured(int,QImage)), this, SLOT(displayImage(int,QImage)));
        connect(ui->buttonCapture, SIGNAL(clicked()), this, SLOT(captureImage()));
        connect(ui->buttonSave, SIGNAL(clicked()), this, SLOT(saveImage()));
        connect(ui->buttonQuit, SIGNAL(clicked()), this, SLOT(close()));
}

Widget::~Widget()
{
        delete ui;
}

void Widget::captureImage()
{
        imageCapture->capture();
}

void Widget::displayImage(int , QImage image)
{
        ui->ImageCapture->setPixmap(QPixmap::fromImage(image));
}

void Widget::saveImage()
{
        QString fileName=QFileDialog::getSaveFileName(this, tr("save file"), "../", tr("Images (*.png *.xpm *.jpg)"));
        //返回的是文件路径字符串  , 第四个参数是设置可以保存的类型
        if(fileName.isEmpty()) {
                return;
        }
        const QPixmap* pixmap=ui->ImageCapture->pixmap();//使用一种画布指向图片
        if(pixmap) {
                pixmap->save(fileName); //保存画布
        }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值