Search code examples
c++cistream

How to dump (write) IStream's content into file (Image)


I have an IStream which I know it contains a PNG file, but I can't write its content into a file like normal I/O stream, I don't know if I am doing something wrong or I should do a different thing for writing IStream into file.

    IStream *imageStream;
    std::wstring imageName;
    packager.ReadPackage(imageStream, &imageName);      

    std::ofstream test("mypic.png");
    test<< imageStream;

Solution

  • Based on the IStream reference you gave here is some untested code that should do roughly what you want:

    void output_image(IStream* imageStream, const std::string& file_name)
    {
        std::ofstream ofs(file_name, std::ios::binary); // binary mode!!
    
        char buffer[1024]; // temporary transfer buffer
    
        ULONG pcbRead; // number of bytes actually read
    
        // keep going as long as read was successful and we have data to write
        while(imageStream->Read(buffer, sizeof(buffer), &pcbRead) == S_OK && pcbRead > 0)
        {
            ofs.write(buffer, pcbRead);
        }
    
        ofs.close();
    }