Boost logo

Boost Users :

Subject: [Boost-users] serialization of an dynamic array to read/write a image in xml
From: Markus Bader (bader_at_[hidden])
Date: 2009-09-22 09:23:39


Hello

I like to store and load images from a xml file.
My problem is now the dynamic array which keeps the image data. I do
not want to copy it into a container and I do not want to go in a for
loop over every pixel.
Any suggestions?
Thanks

Max

#include <fstream>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/serialization/nvp.hpp>

class Image {
public:
    Image()
            : mWidth(0)
            , mHeight(0)
            , mpData(NULL) {
    }
    Image(int width, int height, char *pData)
            : mWidth(width)
            , mHeight(height)
            , mpData(pData) {
    }

    ~Image() {
    }

    template<class archive> void serialize(archive& ar, const unsigned
int version) {
        int i;
        using boost::serialization::make_nvp;
        ar & make_nvp("width", mWidth);
        ar & make_nvp("height", mHeight);
        // ar & make_nvp("data", mpData, mWidth*mHeight); I know this
can not work but --> is there something like this
        //** How can I serialize the serialization array without
making a copy to a container **//
    }

    void save(const std::string& rFileName)    {
        std::ofstream ofs(rFileName.c_str());
        assert(ofs.good());
        boost::archive::xml_oarchive xml(ofs);
        xml << boost::serialization::make_nvp("Image", this);

    }
    void load(const std::string& rFileName)    {
        std::ifstream ifs(rFileName.c_str());
        assert(ifs.good());
        boost::archive::xml_iarchive xml(ifs);
        xml >> boost::serialization::make_nvp("Image", *this);

    }

private:
    int mWidth;
    int mHeight;
    char *mpData;
};

int main ( int argc, char** argv ) {

    int h = 640;
    int w = 480;
    char *p = new char[w*h];
    Image img(w,h,p);
    img.save("/tmp/img.xml");
    img.load("/tmp/img.xml");

    delete p;

    return 0;
}


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net