天天看點

QT調用攝像頭

步驟:

  1. 在.pro檔案下添加兩個子產品。如下:
    QT += multimedia    #這個子產品包含<QCamera><QCameraImageCapture>
    QT += multimediawidgets  #包含<QCameraViewfinder>
    
               
  2. 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
    
    
               
  3. 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); //儲存畫布
            }
    }