2

I received a Image compressed using CCITTFaxDecode. So I used LibTiff.Net from Bit Miracle to be able to convert the image to any format.

I need to write the decompressed image to a MemoryStream. I used a code example from another thread and I was able to use this code

using BitMiracle.LibTiff.Classic;
...   

MemoryStream ms = new MemoryStream();
TiffStream stm = new TiffStream();

Tiff tiff = Tiff.ClientOpen("","w",ms,stm);
tiff.SetField(TiffTag.IMAGEWIDTH, UInt32.Parse(pd.Get(PdfName.WIDTH).ToString()));
tiff.SetField(TiffTag.IMAGELENGTH, UInt32.Parse(pd.Get(PdfName.HEIGHT).ToString()));
tiff.SetField(TiffTag.COMPRESSION, Compression.CCITTFAX4);
tiff.SetField(TiffTag.BITSPERSAMPLE, UInt32.Parse(pd.Get(PdfName.BITSPERCOMPONENT).ToString()));      
tiff.SetField(TiffTag.SAMPLESPERPIXEL, 1);       
tiff.WriteRawStrip(0, raw, raw.Length);  
MemoryStream newStream =   (MemoryStream)tiff.Clientdata();

tiff.Close(); 

The problem I'm having is that the MemoryStream byte array is not a valid image.

I used System.Drawing.Image class to load this newStream memory stream, but there are some null values in the byte array.

If I use the Open constructor to write the image to disk it works fine.

I would like to know if somebody knows why the MemoryStream fails to store the decompressed image.

Thanks

Bobrovsky
  • 13,789
  • 19
  • 80
  • 130
Michael Hidalgo
  • 197
  • 3
  • 13

1 Answers1

1

The problem is:

Tiff object closes and disposes stream after call to Close method.

So, you probably should change

MemoryStream newStream = (MemoryStream)tiff.Clientdata();

to

MemoryStream newStream = new MemoryStream(ms.ToArray());

if you need to use data later.

Another approach is to NOT call Tiff.Close until you are done with the memory stream. this approach has some drawbacks, though.

Bobrovsky
  • 13,789
  • 19
  • 80
  • 130