Как сжать буфер с zlib?
На сайте zlib есть пример использования: http://www.zlib.net/zlib_how.html
Однако в этом примере они сжимают файл. Я хотел бы сжать двоичные данные, хранящиеся в буфере в памяти. Я также не хочу сохранять сжатый буфер на диск.
В основном здесь мой буфер:
fIplImageHeader->imageData = (char*)imageIn->getFrame();
Как сжать его с помощью zlib?
Я был бы признателен за пример кода, как это сделать.
Ответы
Ответ 1
Это пример для упаковки буфера с zlib и сохранения сжатого содержимого в векторе.
void compress_memory(void *in_data, size_t in_data_size, std::vector<uint8_t> &out_data)
{
std::vector<uint8_t> buffer;
const size_t BUFSIZE = 128 * 1024;
uint8_t temp_buffer[BUFSIZE];
z_stream strm;
strm.zalloc = 0;
strm.zfree = 0;
strm.next_in = reinterpret_cast<uint8_t *>(in_data);
strm.avail_in = in_data_size;
strm.next_out = temp_buffer;
strm.avail_out = BUFSIZE;
deflateInit(&strm, Z_BEST_COMPRESSION);
while (strm.avail_in != 0)
{
int res = deflate(&strm, Z_NO_FLUSH);
assert(res == Z_OK);
if (strm.avail_out == 0)
{
buffer.insert(buffer.end(), temp_buffer, temp_buffer + BUFSIZE);
strm.next_out = temp_buffer;
strm.avail_out = BUFSIZE;
}
}
int deflate_res = Z_OK;
while (deflate_res == Z_OK)
{
if (strm.avail_out == 0)
{
buffer.insert(buffer.end(), temp_buffer, temp_buffer + BUFSIZE);
strm.next_out = temp_buffer;
strm.avail_out = BUFSIZE;
}
deflate_res = deflate(&strm, Z_FINISH);
}
assert(deflate_res == Z_STREAM_END);
buffer.insert(buffer.end(), temp_buffer, temp_buffer + BUFSIZE - strm.avail_out);
deflateEnd(&strm);
out_data.swap(buffer);
}
Ответ 2
zlib.h
имеет все необходимые функции: compress
(или compress2
) и uncompress
. См. Исходный код zlib для ответа.
ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen));
/*
Compresses the source buffer into the destination buffer. sourceLen is
the byte length of the source buffer. Upon entry, destLen is the total size
of the destination buffer, which must be at least the value returned by
compressBound(sourceLen). Upon exit, destLen is the actual size of the
compressed buffer.
compress returns Z_OK if success, Z_MEM_ERROR if there was not
enough memory, Z_BUF_ERROR if there was not enough room in the output
buffer.
*/
ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen));
/*
Decompresses the source buffer into the destination buffer. sourceLen is
the byte length of the source buffer. Upon entry, destLen is the total size
of the destination buffer, which must be large enough to hold the entire
uncompressed data. (The size of the uncompressed data must have been saved
previously by the compressor and transmitted to the decompressor by some
mechanism outside the scope of this compression library.) Upon exit, destLen
is the actual size of the uncompressed buffer.
uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
enough memory, Z_BUF_ERROR if there was not enough room in the output
buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. In
the case where there is not enough room, uncompress() will fill the output
buffer with the uncompressed data up to that point.
*/
Ответ 3
Вы можете легко адаптировать этот пример, заменив вызовы fread()
и fwrite()
прямыми указателями на ваши данные. Для сжатия zlib (называемого deflate, как вы "вынимаете весь воздух ваших данных" ) вы выделяете структуру z_stream
, вызываете deflateInit()
, а затем:
- заполните
next_in
следующим фрагментом данных, которые вы хотите сжать.
- установите
avail_in
количество байтов, доступных в next_in
- установите
next_out
туда, где должны быть записаны сжатые данные, которые обычно должны быть указателем внутри вашего буфера, который продвигается по мере продвижения
- установите
avail_out
количество байтов, доступных в next_out
- вызов
deflate
- повторите шаги 3-5 до тех пор, пока
avail_out
не будет равен нулю (т.е. в буфере вывода больше места, чем требуется zlib - больше данных для записи)
- повторите шаги 1-6, пока у вас есть данные для сжатия
В конце концов вы вызываете deflateEnd()
, и все готово.
В основном вы загружаете куски ввода и вывода, пока вы не входите в исходное состояние, и он не работает.
Ответ 4
Это не прямой ответ на ваш вопрос о API zlib, но вы можете быть заинтересованы в библиотеке boost::iostreams
в паре с zlib
.
Это позволяет использовать алгоритмы упаковки zlib
-driven с использованием базовой операции "поток", а затем ваши данные можно легко сжать, открыв некоторый поток памяти и выполнив на нем операцию << data
.
В случае boost::iostreams
это автоматически вызовет соответствующий фильтр упаковки для всех данных, проходящих через поток.