2017-08-27 56 views
0

我在圖像提取中遇到問題。我已經編寫了這個代碼來從word文件中提取所有圖像,但是這些代碼適用於某些圖像意味着它保存了一些圖像文件,但另一方面,此代碼不會從Word文件中提取圖像。我正在使用辦公室互操作庫。從C#中的word文件中提取圖像#

protected void ExtractImage(string imagename, int imagenum) 
    { 

     word.InlineShape shape = oword.ActiveDocument.InlineShapes[imagenum]; 
     int dones = oword.ActiveDocument.InlineShapes.Count;   //Counts number of images in word document 
     for(int i =1 ; i <= dones; i++) 
     { 
      shape = oword.ActiveDocument.InlineShapes[i]; 
      shape.Select(); 
      oword.Selection.Copy(); 

      if (Clipboard.GetDataObject() != null) 
      { 
       IDataObject data = Clipboard.GetDataObject(); 
       if (data.GetDataPresent(DataFormats.Bitmap)) 
       { 
        System.Drawing.Bitmap image = (System.Drawing.Bitmap)data.GetData(typeof(System.Drawing.Bitmap)); 
        image.Save(@"C:\Upload2\" + imagename, System.Drawing.Imaging.ImageFormat.Jpeg); 
        Clipboard.Clear(); 
       } 
      } 
     } 
    } 
+1

*」它確實保存了一些圖像文件,但是另一方面,這段代碼並沒有從Word文件中提取圖像「* - 那麼它會不會提取圖像?你的問題含糊不清。 –

+0

我正在閱讀文件夾中的單詞文件並從中提取所有圖像。此代碼提取所有圖像的80%時間,但錯過文件中圖像的20%時間。 –

+0

是的,我只是閱讀docx文件。 –

回答

-1

我不喜歡與剪貼板搞亂,因爲用戶可能會使用它......

所以,相反我這樣做是使用下面的代碼:

private IEnumerable<Image> GetImagesFromXml(string xml) 
{ 
    XDocument doc = XDocument.Parse(xml); 

    var ns = doc.Root.Name.Namespace; 
    var images = doc.Descendants(ns + "part").Where(a => a.Attribute(ns + "contentType") != null && a.Attribute(ns + "contentType").Value.Contains("image")) 
    .Select(a => new { Name = a.Attribute(ns + "name").Value, Type = a.Attribute(ns + "contentType").Value, D64 = a.Descendants(ns + "binaryData").First().Value, Compression = a.Attribute(ns + "compression").Value }); 

    return images.Select(i => Image.FromStream(new MemoryStream(Convert.FromBase64String(i.D64)), false, false)); 
} 
+0

erm ...爲什麼反對票? –