Qt之生成png/jpg/bmp格式图片
一、问题描述
有时候需要把Qt绘制的一些图形保存为png/jpg/bmp格式的图片,下面就根据自己写的一个简单的测试程序来讲解一下Qt中保存图片的方法。本文主要讲解使用Qpainter和QImage组合使用保存图片的方法。
二、显示效果
1、界面显示效果:
2、生成的图片及图片显示效果:
三、核心代码示例
#include "widget.h"
#include "ui_widget.h"
#include <QPen>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
this->setWindowTitle("测试绘制图片并保存为png/jpg/bmp格式");
drawPicture();
}
Widget::~Widget()
{
delete ui;
}
/// 重写绘制事件,显示在widgt上面
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();
}
/// 绘制图片中
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;
}
/// 保存为图片
void Widget::savePicture(const QString fileName, const char *format)
{
m_image.save(fileName,format);
}
说明:源码下载地址:http://download.csdn.net/download/toby54king/10170570
本文为博主原创文章,未经博主允许请勿转载!作者:ISmileLi