The generation of png/jpg/bmp format picture by Qt

Keywords: Qt

;

1, Problem Description: sometimes it is necessary to save some pictures drawn by Qt as png/jpg/bmp format pictures. Next, according to a simple test program written by myself, I will explain how to save pictures in Qt. This article mainly explains how to use the combination of qpainer and QImage to save pictures.

2, Display effect:

1. Interface display effect:

2. Generated pictures and picture display effect:

3, Core code example:

#include "widget.h"
#include "ui_widget.h"
#include <QPen>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setWindowTitle("Test draw picture and save as png/jpg/bmp format");
    drawPicture();
}

Widget::~Widget()
{
    delete ui;

}

/// Override draw events, shown in widgt Above
void Widget::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
    QPainter *painter = new QPainter(this);
    painter->save();
    QPen pen;
    pen.setWidth(2);
    pen.setColor(Qt::red);
    painter->setPen(pen);
    painter->drawEllipse(QPoint(width()/2,height()/2),50,50);
    painter->drawLine(QPointF(0,0),QPointF(width()/2,height()/2));
    painter->drawRect(QRect(40,40,150,160));
    painter->restore();
    painter->end();
}

/// Drawing pictures
void Widget::drawPicture()
{
    QImage image(QSize(this->width(),this->height()),QImage::Format_ARGB32);
    image.fill("white");
    QPainter *painter = new QPainter(&image);
    painter->save();
    QPen pen;
    pen.setWidth(2);
    pen.setColor(Qt::red);
    painter->setPen(pen);
    painter->drawEllipse(QPoint(width()/2,height()/2),50,50);
    painter->drawLine(QPointF(0,0),QPointF(width()/2,height()/2));
    painter->drawRect(QRect(40,40,150,160));
    painter->restore();
    painter->end();
    m_image = image;
}

/// Save as picture
void Widget::savePicture(const QString fileName, const char *format)
{
    m_image.save(fileName,format);
}

Description: source download address: http://download.csdn.net/download/toby54king/10170570

Posted by articlesocial on Mon, 04 May 2020 09:54:42 -0700