我通过一些功能扩展了 Qt Imageviewer示例。我基本上想添加一个保存功能。在这个例子中,有两个同一个类的函数处理图片打开过程:
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())) {}
}
和
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;
}
所以我在菜单和 ImageViewer.h 类中添加了一个保存按钮:
class ImageViewer : public QMainWindow
{
Q_OBJECT
public:
ImageViewer();
bool loadFile(const QString &);
private slots:
void open();
void print();
void save(); // <---
一切都很好,但我不知道如何在新函数中获取我的图像,除此之外,我显然从 QPixmap 到 QImage 进行了错误的转换 - 但我也尝试将其替换为QPixmap test = imageLabel->pixmap()
没有任何成功。
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());
}
最后,我想将其保存为单色位图(无论之前是什么)。很抱歉发布了很多代码。