简体   繁体   中英

How to compare image (Shape) present in each page of word document through Microsoft.Interop.Word using C#.Net?

I am using following code to replace image (Shape in Microsoft.Interop.Office.Word) of the word document with new image but what the requirement from client is that I need to check the 1st Image of the 1st page of the word document and then compare this image with image of the rest of the document and if match it get replaced with new image else not so need help on how can we compare two shapes(Images)

public void ReplaceWordImage(string FilePath)
        {
            Word.Document d = new Word.Document();
            Word.Application WordApp;
            WordApp = new Microsoft.Office.Interop.Word.Application();
            bool headerImage = false;
            try
            {

                object missing = System.Reflection.Missing.Value;
                object yes = true;
                object no = false;
                object filename = @"D:/ImageToReplace/5.docx";


                d = WordApp.Documents.Open(ref filename, ref missing, ref no, ref missing,
                   ref missing, ref missing, ref missing, ref missing, ref missing,
                   ref missing, ref missing, ref yes, ref missing, ref missing, ref missing, ref missing);
                List<Word.ShapeRange> ranges = new List<Microsoft.Office.Interop.Word.ShapeRange>();
                List<Word.ShapeRange> headerRanges = new List<Microsoft.Office.Interop.Word.ShapeRange>();

  foreach (Word.Shape shape in d.Shapes)
                        {
                            if (shape.Type == Microsoft.Office.Core.MsoShapeType.msoPicture)
                            {
shape.Delete();

foreach (Word.Range r in ranges)
                                `enter code here`    {
                                        r.InlineShapes.AddPicture(@"D:\Untitled.jpg", ref missing, ref missing);
                                        break;

                                    }
}

The Word object model doesn't provide anything to compare two images. The best what you could do is to save both on the disk and then try comparing the bytes representation of both. However, there is a better way to get the job done. The answer is the Open XML SDK which allows getting the bytes representation of images on the fly without saving them to a disk before. The Open XML SDK contains a class WordprocessingDocument that can manipulate a memory stream containing a WordDocument content. And MemoryStream can be converted using ToArray() to a byte[] . See Convert Word of interop object to byte [] without saving physically for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM