我通过一些功能扩展了Qt Imageviewer example。我基本上想要添加一个保存功能。在这个例子中,处理图片打开过程的同一个类有两个函数:
.call()
和
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())) {}
}
所以我在菜单和ImageViewer.h类中添加了一个保存按钮:
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;
}
一切都很好,但我不知道如何在新功能中获取我的图像,除了事实,我显然是从QPixmap到QImage的错误转换 - 但我也尝试用{{替换它1}}没有任何成功。
class ImageViewer : public QMainWindow
{
Q_OBJECT
public:
ImageViewer();
bool loadFile(const QString &);
private slots:
void open();
void print();
void save(); // <---
最后,我想将其保存为单色位图(无论以前是什么)。很抱歉发布了大量代码。
答案 0 :(得分:1)
听起来你的问题是你有一个QPixmap对象,你需要一个QImage对象。如果是这种情况,那么您可以在QPixmap上convert a QPixmap into a QImage by calling the toImage() method;它将返回生成的QImage对象。
至于将QImage转换为单色位图,您应该可以通过调用QImage上的convertToFormat(QImage::Format_Mono)来实现。该调用将返回QImage的新(1位)版本。