1、编译zlib库
1.1、下载zlib
官方下载地址:下载链接
百度云盘下载:链接: https://pan.baidu.com/s/10Ix0xxYj-oG7gHCFJB-0Zg 提取码: em2w 复制这段内容后打开百度网盘手机App,操作更方便哦
1.2、编译zlib库文件
- 将win32\makefile.gcc拷贝到zlib源码的根目录
- 使用QtCreator集成安装的mingw编译zlib
- 命令: mingw32-make -f makefile.gcc
- 将生成的libz.a和zlib1.dll
- 将libz.a、zlib1.dll、zlib.h、zconf.h复制到项目文件夹中
2、Qt导入外部库
通过QtCreator 右键项目->添加库->外部库
3、代码示例
#include "mainwindow.h"
#include <QApplication>
#include "zlib.h"
#include "zconf.h"
#include <QDebug>
#include <QFile>
QByteArray GzipCompress(QByteArray postBody)
{
QByteArray outBuf;
z_stream c_stream;
int err = 0;
int windowBits = 15;
int GZIP_ENCODING = 16;
if (!postBody.isEmpty())
{
c_stream.zalloc = (alloc_func)0;
c_stream.zfree = (free_func)0;
c_stream.opaque = (voidpf)0;
c_stream.next_in = (Bytef *)postBody.data();
c_stream.avail_in = postBody.size();
if (deflateInit2(&c_stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED,
MAX_WBITS + GZIP_ENCODING, 8, Z_DEFAULT_STRATEGY) != Z_OK) return QByteArray();
for (;;) {
char destBuf[4096] = { 0 };
c_stream.next_out = (Bytef *)destBuf;
c_stream.avail_out = 4096;
int err = deflate(&c_stream, Z_FINISH);
outBuf.append(destBuf, 4096 - c_stream.avail_out);
if (err == Z_STREAM_END || err != Z_OK)
{
break;
}
}
auto total = c_stream.total_out;
deflateEnd(&c_stream);
total = c_stream.total_out;
}
return outBuf;
}
QByteArray GZipUnCompress(QByteArray src)
{
QByteArray outBuffer;
z_stream strm;
strm.zalloc = NULL;
strm.zfree = NULL;
strm.opaque = NULL;
strm.avail_in = src.size();
strm.next_in = (Bytef *)src.data();
int err = -1, ret = -1;
err = inflateInit2(&strm, MAX_WBITS + 16);
qDebug() << "err = " << err;
if (err == Z_OK) {
while (true)
{
char buffer[4096] = { 0 };
strm.avail_out = 4096;
strm.next_out = (Bytef *)buffer;
int code = inflate(&strm, Z_FINISH);
outBuffer.append(buffer, 4096 - strm.avail_out);
// qDebug()<<"ddd"<<code<<Z_OK;
if (Z_STREAM_END == code )
{
break;
}
}
}
inflateEnd(&strm);
return outBuffer;
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QString str = "hello world";
QByteArray compress = GzipCompress(str.toUtf8());
QByteArray uncompress = GZipUnCompress(compress);
qDebug() << QString(uncompress);
return a.exec();
}
4、示例链接
链接: https://pan.baidu.com/s/110W0hoK2cG7yV6ie5u73fw 提取码: s45b 复制这段内容后打开百度网盘手机App,操作更方便哦