Search code examples
c#spreadsheettiffembedded-resourceopenxml-sdk

Embedding Image as new ImagePart creates a .bin file using Open XML SDK


I am developing code using a spreadsheet input file, a MemoryStream, Open XML SDK and ImageMagick to:

  1. Read stream of an embedded image file in a spreadsheet
  2. Convert stream to TIFF file format
  3. Embed new image in package as a file and simultaneously as a new ImagePart
  4. Change relationships of image controls (Blip.Embed) to point from old image to new image
  5. Delete old image by deleting the ImagePart

I got all of it working EXCEPT the new file created from the memorystream is saved as image.bin instead of image.tiff even though I specify the ImagePartType as Tiff:

ImagePart new_ImagePart = worksheetPart.AddImagePart(ImagePartType.Tiff);

The new Uri of the ImagePart will be xl/media/image.bin but it should be xl/media/image.tiff.

I use this code to feed data from stream to the new ImagePart:

stream.Position = 0;
new_ImagePart.FeedData(stream);

When I extract the new embedded file from the package and change extension to .tiff the image is read and I can validate the TIFF as well-formed by using a TIFF validator.

Can anyone help me change this behaviour? I have read it is not possible to rename embedded files inside the package, so the name should be given at genesis.

PS. The files are perfectly replaced and shown in the spreadsheet when opening it in Excel, but the underlying files does not have correct extension, and I would like to fix this.

PPS. The embedded files I want to convert were saved using Excel and are saved as JPEG and PNG with their correct extensions in the package as image4.jpg and image5.png


Solution

  • The developers of Open XML SDK have recognized this as a bug and created a fix.

    For reference to issue: https://github.com/dotnet/Open-XML-SDK/issues/1305