qt--压缩图片的大小

该函数 是输入图片的字节流 然后再内部转换后输出文件的字节流

头文件部分

cpp 复制代码
    /*!
     * @brief compressImage
     * @param format    图片的压缩格式
     * @param imageByteArray    源图像字节流
     * @param fileSize  压缩指定的文件大小 默认180kb
     * @param limitHeight 限制图片的高度
     * @return QByteArray  压缩后的图片字节流
     */
    static QByteArray compressImage(const QByteArray imageByteArray, const char *format = nullptr, int fileSize = 180 * 1024, int limitHeight = 1000);

实现部分

cpp 复制代码
QByteArray ImageUtil::compressImage(const QByteArray imageByteArray, const char *format, int fileSize, int limitHeight) {
    qInfo() << "传入图片大小" << imageByteArray.size();
    if (imageByteArray.size() < fileSize) {
        qInfo() << "图片满足要求,无需压缩";
        return imageByteArray;
    }
    qInfo() << "开始压缩图片";
    int quality = 100;
    QImage srcImg;
    QPixmap pixmap;
    srcImg.loadFromData(imageByteArray);
    QBuffer buff;
    double scale = 1;
    QSize imgSize = srcImg.size();
    // 压缩图片的尺寸 控制在limitHeight以内
    if (imgSize.height() > limitHeight)
        scale = ( double )limitHeight / ( double )imgSize.height();
    imgSize = imgSize.scaled(imgSize.width() * scale, imgSize.height() * scale, Qt::IgnoreAspectRatio);
    // 图片等比例缩放
    pixmap = pixmap.fromImage(srcImg.scaled(imgSize, Qt::IgnoreAspectRatio, Qt::FastTransformation));
    // 压缩图片的质量 控制在fileSize之内
    qint64 fsz;
    while (true) {
        QBuffer tempBuff;
        // 图片降低质量
        bool isOk = pixmap.save(&tempBuff, format, quality);
        quality = quality - 2;
        if (quality <= 0)
            break;
        fsz = tempBuff.size();
        if (isOk) {
            if (fsz <= fileSize) {
                pixmap.save(&buff, format, quality);
                break;
            }
        }
    }
    qInfo() << "现在图片大小" << fsz << "要求图片大小" << fileSize << "质量系数" << quality << "图片宽高" << imgSize.width() << imgSize.height();
    return buff.data();
}
相关推荐
blasit3 小时前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
范特西.i5 天前
QT聊天项目(8)
开发语言·qt
枫叶丹45 天前
【Qt开发】Qt界面优化(七)-> Qt样式表(QSS) 样式属性
c语言·开发语言·c++·qt
十五年专注C++开发5 天前
Qt deleteLater作用及源码分析
开发语言·c++·qt·qobject
kangzerun5 天前
SQLiteManager:一个优雅的Qt SQLite数据库操作类
数据库·qt·sqlite
金刚狼885 天前
qt和qt creator的下载安装
开发语言·qt
追烽少年x5 天前
Qt中使用Zint库显示二维码
qt
谁刺我心5 天前
qt源码、qt在线安装器镜像下载
开发语言·qt
金刚狼885 天前
在qt creator中创建helloworld程序并构建
开发语言·qt
扶尔魔ocy6 天前
【转载】QT使用linuxdeployqt打包
开发语言·qt