我正在QPainter的帮助下垂直组合2个QImage(“ firstImage”和“ secondImage”)。从屏幕截图中可以看到,组合图像正确显示,没有错误:
Combined Image Displays Properly
但是,如果我想使用.save存储“ combinedImage”,则程序会暂停并出现断言错误。
如何将合并的图像存储到硬盘中?
mainwindow.cpp:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPainter>
#include <QImage>
#include <QPaintEvent>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::paintEvent(QPaintEvent *)
{
QString firstImagePath = "/home/nvidia/Desktop/TestFolder/firstImage.jpg";
QString secondImagePath = "/home/nvidia/Desktop/TestFolder/secondImage.jpg";
QImage firstImage(firstImagePath);
QImage secondImage(secondImagePath);
QImage combinedImage;
QPainter paint(this);
paint.begin(&combinedImage);
paint.drawImage(0, 0, firstImage);
paint.drawImage(0, firstImage.height()*1.1, secondImage);
paint.end();
bool i = firstImage.save("/home/nvidia/Desktop/TestFolder/firstImage-Copy.bmp");
Q_ASSERT(i);
bool j = combinedImage.save("/home/nvidia/Desktop/TestFolder/combinedImage-Copy.bmp");
Q_ASSERT(j);
}
mainwindow.h:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
void paintEvent(QPaintEvent *);
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
这是Qt输出:
Starting /home/nvidia/qtprojects/build-CombinedSave-Jetson_TX2-Debug/CombinedSave...
QPainter::begin: Painter already active
ASSERT: "j" in file ../CombinedSave/mainwindow.cpp, line 39
The program has unexpectedly finished.
/home/nvidia/qtprojects/build-CombinedSave-Jetson_TX2-Debug/CombinedSave crashed
firstImage-Copy.bmp存储在TestFolder中,而CombinedImage-Copy.bmp没有存储。.
我的一些系统和程序属性:
ARMv8 Processor rev 3 (v8l) × 4 ARMv8 Processor rev 0 (v8l) × 2
Ubuntu 16.04 LTS
Qt Creator 3.5.1 Based on Qt 5.5.1 (GCC 5.2.1 20151129, 64 bit)
答案 0 :(得分:1)
考虑代码...
QPainter paint(this);
paint.begin(&combinedImage);
第一行实际上是...
QPainter paint;
paint.begin(this);
,并在QPainter
(您的this
实例)上激活MainWindow
。但是你有...
paint.begin(&combinedImage);
再次调用已激活的QPainter::begin
上的QPainter
。这可能是错误消息的来源...
QPainter :: begin:画家已经激活
此外,您还使用默认的combinedImage
构造函数初始化QImage
...
QImage combinedImage;
在这一点上,combinedImage
是一个空图像-它没有大小或格式,并且不能按原样使用。
要初始化并呈现combinedImage
,请尝试...
QImage combinedImage(std::max(firstImage.width(), secondImage.width()), /* Width */
firstImage.height() + secondImage.height(), /* Height */
QImage::Format_ARGB32_Premultiplied); /* Format */
{
QPainter paint(&combinedImage);
paint.drawImage(0, 0, firstImage);
paint.drawImage(0, firstImage.height(), secondImage);
}