How to do it…

Qt's built-in image libraries make image conversion really simple:

  1. Open Qt Creator and create a new Qt Widgets Application project.
  2. Open mainwindow.ui and add a line edit and push button to the canvas to select image files, a combo box to select the desired file format, and another push button to start the conversion process:

  1. Double-click the combo box and a window will appear where you can edit the combo box. We will add three items to the combo box list by clicking the + button three times and renaming the items PNG, JPEG, and BMP:

  1. Right-click on one of the push buttons and select Go to slot…, then click the OK button. A slot function will be automatically added to your source files. Repeat this step for the other push button as well:

  1. Let's move over to the source code. Open mainwindow.h and add in the following header:
#include <QMainWindow>
#include <QFileDialog>
#include <QMessageBox>
#include <QDebug>
  1. Open mainwindow.cpp and define what will happen when the Browse button is clicked, which in this case is opening the file dialog to select an image file:
void MainWindow::on_browseButton_clicked() {
QString fileName = QFileDialog::getOpenFileName(this, "Open Image", "", "Image Files (*.png *.jpg *.bmp)");
ui->filePath->setText(fileName);
}
  1. Define what will happen when the Convert button is clicked:
void MainWindow::on_convertButton_clicked() {
QString fileName = ui->filePath->text();
if (fileName != "") {
QFileInfo fileInfo = QFile(fileName);
QString newFileName = fileInfo.path() + "/" + fileInfo.completeBaseName();
QImage image = QImage(ui->filePath->text());
if (!image.isNull()) {
  1. Check which format is being used:
            // 0 = PNG, 1 = JPG, 2 = BMP
int format = ui->fileFormat->currentIndex();
if (format == 0) {
newFileName += ".png";
}
else if (format == 1) {
newFileName += ".jpg";
}
else if (format == 2) {
newFileName += ".bmp";
}

  1. Check whether the image has been converted:
            qDebug() << newFileName << format;
if (image.save(newFileName, 0, -1)) {
QMessageBox::information(this, "Success", "Image successfully converted.");
}
else {
QMessageBox::warning(this, "Failed", "Failed to convert image.");
}
}
  1. Display the message boxes:
        else {
QMessageBox::warning(this, "Failed", "Failed to open image file.");
}
}
else {
QMessageBox::warning(this, "Failed", "No file is selected.");
}
}
  1. Build and run the program now, and we should get a pretty simple image converter that looks like this:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset