c++ compress byte array
Greetings all,
I load set of images and generate volume data.I save this volume data in a
unsigned char *volume
array.
Now I want to save this array in a file and retrieve.But before saving I want to compress the byte array since 开发者_JAVA百科the volume data is huge.
Any tips on this?
Thanks in advance.
volume
in your example is not an array. As for compression, there are books written on the topic. For something quick and easy to use with C++, check out the boost.iostream library, which comes with zlib, gzip, and bzip2 compressors.
To offset my nitpicking, here's an example (changing to char
because it's a lot more verbose with unsigned char
s)
#include <fstream>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/filter/bzip2.hpp>
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/copy.hpp>
namespace io = boost::iostreams;
int main()
{
const size_t N = 1000000;
char* volume = new char[N];
std::fill_n(volume, N, 'a'); // 100,000 letters 'a'
io::stream< io::array_source > source (volume, N);
{
std::ofstream file("volume.bz2", std::ios::out | std::ios::binary);
io::filtering_streambuf<io::output> outStream;
outStream.push(io::bzip2_compressor());
outStream.push(file);
io::copy(source, outStream);
}
// at this point, volume.bz2 is written and closed. It is 48 bytes long
}
It depends on the type of data. If the images are already compressed (jpeg, png, etc), then it won't compress anymore.
You could use zlib http://www.zlib.net/ for uncompressed images, but I'd suggest to compress each of them with something specialized on images.
Edit:
1) Lossy compression will give much higher compression rates.
2) You mentioned that they are the same size. Are they also similar? A video codec would be the best choise in that case.
You will need to use a 3rd party api (as already suggested). If this is C++/CLI you can use zlib.net, but if not then you will need some other library like gzip or lzma.
Here is a link for 7-zip sdk: http://www.7-zip.org/sdk.html
精彩评论