BitmapEncoder: “The image has corrupted metadata header.” “The image metadata header is unrecognized.”

Background:

I have 2 .tiff image files and I want to merge them into one .tiff file.  I use TIffBitmapEncoder.  I use TiffBitmapDecoder to decode the file memory stream and add to encoder.Frames.

Problem:

When I try to use the encoder to Save() to the output filestream, I get an argument exception saying “The image has corrupted metadata header.” with an inner exception “The image metadata header is unrecognized.”

Solution:

Load the input memory stream into a bitmap and save it to another temporary memory stream.  It seems to fix the header.  Then you use this fixed memory stream for the decoder.

Below is some of my partial code.  You need to create the output filestream and close all the memory stream and dispose, etc.

   1: TiffBitmapEncoder encoder = new TiffBitmapEncoder();

   2:  

   3: encoder.Compression = TiffCompressOption.Default;

   4:  

   5: MemoryStream convertedMemoryStream = new MemoryStream();

   6: var bitmap = new Bitmap(ms); // input memory stream

   7:  

   8: bitmap.Save(convertedMemoryStream, ImageFormat.Tiff); // save it again as a tiff, hoping it fixes the header meta data

   9: ms.Position = 0;

  10: convertedMemoryStream.Position = 0;

  11:  

  12: var decoder = new TiffBitmapDecoder(convertedMemoryStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);

  13: bitmapSource = decoder.Frames[0];

  14:  

  15: encoder.Frames.Add(BitmapFrame.Create(bitmapSource));

  16:  

  17: encoder.Save(sTiff); // sTiff is a FileStream to the output file

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s