• 492阅读
  • 0回复

zhengtianzuo系列-Qt调用zlib压缩解压文件 [复制链接]

上一主题 下一主题
离线zhengtianzuo
 

只看楼主 倒序阅读 楼主  发表于: 2017-12-22
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
人生很短暂,只做好一件事,并且把它做到极致。
快速回复
限100 字节
 
上一个 下一个