I expanded the Qt Imageviewer example by some functionality. I basically want to add a save function. In this example there are two functions of the same class handling the picture open process:
void ImageViewer::open()
{
QStringList mimeTypeFilters;
foreach (const QByteArray &mimeTypeName, QImageReader::supportedMimeTypes())
mimeTypeFilters.append(mimeTypeName);
mimeTypeFilters.sort();
const QStringList picturesLocations = QStandardPaths::standardLocations(QStandardPaths::PicturesLocation);
QFileDialog dialog(this, tr("Open File"),
picturesLocations.isEmpty() ? QDir::currentPath() : picturesLocations.last());
dialog.setAcceptMode(QFileDialog::AcceptOpen);
dialog.setMimeTypeFilters(mimeTypeFilters);
dialog.selectMimeTypeFilter("image/jpeg");
while (dialog.exec() == QDialog::Accepted && !loadFile(dialog.selectedFiles().first())) {}
}
and
bool ImageViewer::loadFile(const QString &fileName)
{
QImageReader reader(fileName);
reader.setAutoTransform(true);
const QImage image = reader.read();
if (image.isNull()) {
QMessageBox::information(this, QGuiApplication::applicationDisplayName(),
tr("Cannot load %1.").arg(QDir::toNativeSeparators(fileName)));
setWindowFilePath(QString());
imageLabel->setPixmap(QPixmap());
imageLabel->adjustSize();
return false;
}
imageLabel->setPixmap(QPixmap::fromImage(image));
scaleFactor = 1.0;
printAct->setEnabled(true);
fitToWindowAct->setEnabled(true);
convAct->setEnabled(true); // so the image can be converted if it was loaded ...
updateActions();
if (!fitToWindowAct->isChecked()) {
imageLabel->adjustSize();
}
setWindowFilePath(fileName);
return true;
}
So I added a save button in the menus, and in the ImageViewer.h class:
class ImageViewer : public QMainWindow
{
Q_OBJECT
public:
ImageViewer();
bool loadFile(const QString &);
private slots:
void open();
void print();
void save(); // <---
Everything is fine, but I don't know how to get my Image in the new function, besides the fact, that I obviously make a wrong conversion from QPixmap to QImage - but I also tried replacing it with QPixmap test = imageLabel->pixmap()
without any success.
void ImageViewer::save()
{
QImage test = imageLabel->pixmap();
qWarning()<< test;
QByteArray bytes;
QBuffer buffer(&bytes);
buffer.open(QIODevice::WriteOnly);
image.save(&buffer, "BMP");
QString monobitmap = QString::fromLatin1(bytes.toBase64().data());
}
In the end, I want to save it as a monochrome bitmap (no matter what it was before). Sorry for posting a lot of code.
It sounds like your problem is that you have a QPixmap object and you need a QImage object. If that's the case, then you can convert a QPixmap into a QImage by calling the toImage() method on the QPixmap; it will return the resulting QImage object.
As for you converting the QImage to a monochrome bitmap, you should be able to do that by calling convertToFormat(QImage::Format_Mono) on your QImage. That call will return the new (1-bit) version of the QImage.