Qt QImageWriter类介绍

1.简介

QImageWriter 用于写入图像文件的类。它提供了将 QImage 对象保存到不同图像格式文件的功能,包括但不限于 PNG、JPEG、BMP 等。QImageWriter 可以将图像写入文件,也可以写入任何 QIODevice,如 QByteArray,这使得它非常灵活。

主要特点:

  • 格式支持: 支持多种图像格式,并且可以指定写入的图像格式。
  • 写入控制: 可以通过指定大小、质量、压缩比等选项来控制写入过程。
  • 错误处理: 提供了错误处理机制,可以捕获和处理写入过程中的错误。
  • 元数据支持: 可以设置图像的元数据,如分辨率、注释等信息。

2.常用接口介绍

  • canWrite():判断是否能够写入图像。
  • write():将 QImage 对象写入文件或设备。
  • setFormat():设置写入的图像格式。
  • setQuality():对于支持质量设置的图像格式(如 JPEG),设置图像质量。
  • setCompression():对于支持压缩设置的图像格式(如 PNG),设置图像压缩级别。
  • errorString():获取错误的字符串描述。

3.示例

cpp 复制代码
#include "widget.h"
#include "ui_widget.h"
#include <QFile>
#include <QImageReader>
#include <QImageWriter>
#include <QDebug>
#include <QFileDialog>

QImage g_image; //全局的

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_pushButton_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this,
          tr("Open Image"), "D:/", tr("Image Files (*.png *.jpg *.bmp *.jpeg)"));

    if(fileName.isEmpty())
        return;

    QFile file(fileName);
    file.open(QIODevice::ReadOnly);

    QImageReader reader(&file);
    if (!reader.canRead())
    {
       qDebug() << "Cannot read the image";
       return;
    }

    g_image = reader.read();
    if (g_image.isNull())
    {
       qDebug() << "Failed to read the image:" << reader.errorString();
       return;
    }

    ui->lbImage->setPixmap(QPixmap::fromImage(g_image));
}

void Widget::on_pushButton_2_clicked()
{
    if (g_image.isNull())
    {
       qDebug() << "image is null";
       return;
    }

    QFile file("./test.jpg");
    file.open(QIODevice::WriteOnly);

    QImageWriter writer(&file, "jpg");
    writer.setQuality(85); // 设置 JPEG 图像质量为 85%

    if (!writer.write(g_image))
    {
        qDebug() << "Failed to write the image:" << writer.errorString();
        return;
    }
}

4.更多参考

libVLC 专栏介绍-CSDN博客

Qt+FFmpeg+opengl从零制作视频播放器-1.项目介绍_qt opengl视频播放器-CSDN博客

QCharts -1.概述-CSDN博客

Qt QImageReader类介绍-CSDN博客

相关推荐
倒头就睡的小比特3 天前
算法竞赛C++常用的STL
c++·算法
weilx12343 天前
C++笔记-文件IO-<fcntl.h>
c++
小羊没烦恼!3 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
伞伞悦读3 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
Smileyqp沛沛3 天前
前端?C++ ?较大差异基础罗列
c++·基础·前端转c++
C语言小火车3 天前
C/C++ 为什么需要编译器?
开发语言·c++
旖旎夜光3 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
吞下星星的少年·-·3 天前
C++ 萌新语法入门篇
c++·算法比赛
霍霍的袁3 天前
【C++】map 和 set 的使用 | 从用法到底层
开发语言·c++·学习·visual studio
another heaven3 天前
【算法/C++ MD5算法能否逆解码?原理、C++实现与同类哈希算法对比】
c++·算法·哈希算法