We have learned how to connect to our camera using Qt's multimedia module in the previous section. Now, we will try and capture a still image from the camera and save it into a JPEG file. It's actually very very simple with Qt.
First, open mainwindow.h and add the following variable:
private: Ui::MainWindow *ui; QCamera* camera; QCameraViewfinder* viewfinder; QCameraImageCapture* imageCapture; bool connected;
Then, right-click on the Capture button in mainwindow.ui and select Go to slot.... Then, select clicked() and press OK. Now, a new slot function will be created for you in mainwindow.cpp. Add the following code to capture an image from the camera:
void MainWindow::on_captureButton_clicked() { if (connected) { imageCapture = new QCameraImageCapture(camera); camera->setCaptureMode(QCamera::CaptureStillImage); camera->searchAndLock(); imageCapture->capture(qApp->applicationDirPath()); camera->unlock(); } }
What we did in the preceding code is basically create a new QCameraImageCapture object and set its media object as the active camera. Then, set its capture mode as a still image. Before we ask the QCameraImageCapture object to capture an image, we must lock the camera so that the settings remain unchanged during the process of capturing the image. You may unlock it by calling camera->unlock() after you have successfully captured the image.
We used qApp->applicationDirPath() to get the application directory so that the image will be saved alongside the executable file. You can change this to whatever directory you want. You can also put your desired filename behind the directory path; otherwise, it will save the images sequentially using the default filename format starting with IMG_00000001.jpg, IMG_00000002.jpg, and so on.