0

我通过一些功能扩展了 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());
}   

最后,我想将其保存为单色位图(无论之前是什么)。很抱歉发布了很多代码。

4

1 回答 1

1

听起来你的问题是你有一个 QPixmap 对象并且你需要一个 QImage 对象。如果是这种情况,那么您可以通过调用 QPixmap 上的 toImage() 方法将 QPixmap 转换为 QImage;它将返回生成的 QImage 对象。

至于将 QImage 转换为单色位图,您应该可以通过在 QImage 上调用convertToFormat(QImage::Format_Mono)来做到这一点。该调用将返回 QImage 的新(1 位)版本。

于 2016-01-09T03:51:26.443 回答