查看完整版本: [-- zhengtianzuo系列-Qt调用zlib压缩解压文件 --]

QTCN开发网 -> Qt代码秀 -> zhengtianzuo系列-Qt调用zlib压缩解压文件 [打印本页] 登录 -> 注册 -> 回复主题 -> 发表主题

zhengtianzuo 2017-12-22 09:28

zhengtianzuo系列-Qt调用zlib压缩解压文件

zlib提供compress uncompress 两个函数分别是压缩和解压

```
ZEXTERN int ZEXPORT compress OF((Bytef *dest,   uLongf *destLen,
                                 const Bytef *source, uLong sourceLen));
```

```
ZEXTERN int ZEXPORT uncompress OF((Bytef *dest,   uLongf *destLen,
                                   const Bytef *source, uLong sourceLen));
```

压缩前可以通过compressBound函数来预测压缩后的数据大小

```
    QFile file("SilkPlatform.png");
    file.open(QIODevice::ReadOnly);
    QByteArray bytes = file.readAll();
    file.close();
    int nDataSize = bytes.size();
    char *cData = new char[nDataSize];
    memcpy(cData, bytes.data(), nDataSize);
    int nCompSize = compressBound(nDataSize);
    char *cComp = new char[nCompSize];

    //压缩
    if (zlibCompress(cComp, nCompSize, cData, nDataSize) != Z_OK)
    {
        printf("compress failed!\n");
        return -1;
    }

    //解压
    memset(cData, 0, nDataSize);
    if (zlibUncompress(cData, nDataSize, cComp, nCompSize) != Z_OK)
    {
        printf("uncompress failed!\n");
        return -1;
    }

    delete[] cComp;

    QFile fileOut("SilkPlatformOut.png");
    fileOut.open(QIODevice::WriteOnly);
    fileOut.write(reinterpret_cast<char*>(cData), nDataSize);
    fileOut.close();

    delete[] cData;
```


需要完整代码请访问 QtOtherExamples

big_mouse 2020-04-23 09:16


查看完整版本: [-- zhengtianzuo系列-Qt调用zlib压缩解压文件 --] [-- top --]



Powered by phpwind v8.7 Code ©2003-2011 phpwind
Gzip disabled