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();
}
相关推荐
用户805533698035 天前
不止三件套:QObject 属性系统全关键字与运行时反射!
c++·qt
xcyxiner5 天前
DicomViewer (vcpkg Windows和ubuntu编译)7
qt
Quz10 天前
QML Hello World 入门示例
qt
xcyxiner13 天前
DicomViewer (dcmtk读取dcm文件)5
qt
xcyxiner13 天前
DicomViewer (后台线程处理文件)4
qt
xcyxiner14 天前
DicomViewer (添加模型类)3
qt
xcyxiner14 天前
DicomViewer (目录调整) 2
qt
xcyxiner14 天前
dcmtk vtk vtk-dicom(gdcm) 编译(debug) v2
qt
桥田智能16 天前
桥田智能 QT-650S:面向白车身焊装的 800kg 重载快换解决方案
开发语言·qt·系统架构
森G16 天前
75、服务器源码解析---------云视频服务项目
linux·服务器·网络·c++·qt