使用boost zlib从std :: vector中的文件读取压缩的zraw数据

时间:2017-05-23 08:24:16

标签: c++ boost zlib

我正在尝试使用boost和zlib读取压缩(3d体素化图像)文件但到目前为止没有成功。

我的目标是解压缩数据并将它们存储在std :: vector中。此任务是否有更具体的示例,而不是boost文档的示例?

以下是我尝试做的一个示例:

std::vector<DATATYPE> data;

{
  ifstream file_in("image.zraw", ios_base::in | ios_base::binary);
  filtering_istream in;
  in.push(zlib_decompressor());
  in.push(file_in);

  //copy somehow memory from in the vector data... DATATYPE is the type of data to be stored in the vector...
}

提前致谢, 康斯坦丁诺

2 个答案:

答案 0 :(得分:0)

由于你无法指定,我只是假设:

<强> Live On Coliru

#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/filter/zlib.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <fstream>

namespace bio = boost::iostreams;

template <typename T>
void write_data(std::string const& fname, std::vector<T> const& data) {
    std::ofstream ofs(fname, std::ios_base::binary);
    bio::filtering_ostream out;

    out.push(bio::zlib_compressor());
    out.push(ofs);

    boost::archive::binary_oarchive oa(out);
    oa << data;
}

template <typename T>
std::vector<T> read_data(std::string const& fname) {
    std::vector<T> result;

    std::ifstream file_in(fname, std::ios_base::binary);
    bio::filtering_istream in;

    in.push(bio::zlib_decompressor());
    in.push(file_in);

    boost::archive::binary_iarchive ia(in);
    ia >> result;

    return result;
}

#include <iostream>

int main() {
    write_data("floats.zraw", std::vector<float> { 1,2,3 });
    write_data("ints.zraw",   std::vector<int>   { 4,5,6 });

    auto floats = read_data<float>("floats.zraw");
    auto ints   = read_data<int>("ints.zraw");

    std::copy(floats.begin(), floats.end(), std::ostream_iterator<float>(std::cout << '\n', " "));
    std::copy(ints  .begin(), ints  .end(), std::ostream_iterator<int  >(std::cout << '\n', " "));
}

打印

1 2 3
4 5 6

它使用Boost Serialization和Boost Iostreams来实现二进制(反)序列化为压缩文件。格式通用,不仅限于POD数据类型,也不限于平台/库版本。

答案 1 :(得分:0)

解决我的问题我发布可能对其他人有帮助的答案

 previous stuff.....

// Clear the data storing vector of the image.
this->data_.clear();

// Reserve enough space for the data vector according to image's size.
this->data_.reserve(this->num_voxels_);

// Here happens the decompression.
{
std::ifstream file_in("../data/image.zraw", std::ios::in | std::ios_base::binary);
boost::iostreams::filtering_istream in;

in.push(boost::iostreams::zlib_decompressor());
in.push(file_in);

// Write the data from the filtering istream to the data_ vector.
char *dptr = reinterpret_cast<char*>(this->data_.data());

// DATATYPE is the templated storage type of the vector.
for(int i=0;i<sizeof(DATATYPE)*this->num_voxels_;i++)
    in.read(&dptr[i],1);
}

next stuff.......