This project has moved. For the latest updates, please go here.

problem adding images with DocX.AddImage

Dec 8, 2009 at 5:44 AM
Edited Dec 8, 2009 at 5:58 PM

I am getting an exception when trying to add an image from a Stream. I wonder if I am doing something incorrectly or if there is an issue with DocX?

sample code (image.data is a System.Data.Linq.Binary containing the binary image data).

 foreach (var image in results)
                    {
                        using (Stream s = new MemoryStream(image.data.ToArray()))
                        {
                            Novacode.Image img = doc.AddImage(s);
                            Picture pic = p.InsertPicture(img.Id);
                        }
                       
                    }

Exception is as follows:

Exception Details: System.InvalidOperationException: Cannot add part for the specified URI because it is already in the package.

[InvalidOperationException: Cannot add part for the specified URI because it is already in the package.]
   System.IO.Packaging.Package.CreatePart(Uri partUri, String contentType, CompressionOption compressionOption) +703690
   System.IO.Packaging.Package.CreatePart(Uri partUri, String contentType) +10
   Novacode.DocX.AddImage(Object o) in ..\docx\DocX\DocX.cs:1869
   Novacode.DocX.AddImage(Stream stream)

 

Dec 8, 2009 at 6:31 PM
Edited Dec 8, 2009 at 6:32 PM

I remedied this issue by making the following code change to the DocX.AddImage() method:

 

Guid name = Guid.NewGuid();

// Create a new image part. 

//PackagePart img = package.CreatePart(new Uri(string.Format("/word/media/image{0}.jpeg", max + 1), UriKind.Relative), System.Net.Mime.MediaTypeNames.Image.Jpeg);  

PackagePart img = package.CreatePart(new Uri(string.Format("/word/media/image{0}.jpeg", name), UriKind.Relative), System.Net.Mime.MediaTypeNames.Image.Jpeg);

Coordinator
Jan 26, 2010 at 6:35 PM

Chickendelicious,

I will make sure that this fix is added to the next release and that you are credited for it.

Kind regards,

Cathal