C++ LibTiff - Read and Save file from and to Memory

Van Coding picture Van Coding · Jan 7, 2011 · Viewed 14.4k times · Source

Is there a way in LibTiff how I can read a file from Memory and save it to Memory?

I don't want to save the image to the disc first, before opening it with an other library...

Thanks so much!

Answer

KSletmoe picture KSletmoe · Aug 10, 2012

I know this is an old question, but I am going to post an easier, more up-to-date answer for those like myself who need this information for more recent versions of libtiff. In the newest version of libtiff (4.0.2), and even the past few versions I believe (check for your specific version number), there is an include file called tiffio.hxx. It has two extern functions for reading/writing to streams in memory:

extern TIFF* TIFFStreamOpen(const char*, std::ostream *);
extern TIFF* TIFFStreamOpen(const char*, std::istream *);

You can just include this file and read or write to memory.

Writing example:

#include <tiffio.h>
#include <tiffio.hxx>
#include <sstream>    

std::ostringstream output_TIFF_stream;

//Note: because this is an in memory TIFF, just use whatever you want for the name - we 
//aren't using it to read from a file
TIFF* mem_TIFF = TIFFStreamOpen("MemTIFF", &output_TIFF_stream);

//perform normal operations on mem_TIFF here like setting fields
//...

//Write image data to the TIFF 
//..

TIFFClose(mem_TIFF);   

//Now output_TIFF_stream has all of my image data. I can do whatever I need to with it.

Reading is very similar:

#include <tiffio.h>
#include <tiffio.hxx>
#include <sstream>

std::istringstream input_TIFF_stream;
//Populate input_TIFF_stream with TIFF image data
//...

TIFF* mem_TIFF = TIFFStreamOpen("MemTIFF", &input_TIFF_stream);

//perform normal operations on mem_TIFF here reading fields
//...

TIFFClose(mem_TIFF);

These are very simple examples, but you can see that by using TIFFStreamOpen you don't have to override those functions and pass them to TIFFClientOpen.