从C#中的word文件中提取图像

时间:2017-08-27 11:56:17

标签: c# ms-word office-interop

我在图像提取方面遇到了问题。我已经编写了这段代码来从word文件中提取所有图像,但是这段代码适用于某些图像意味着它确实保存了一些图像文件,但另一方面,这段代码不能从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 个答案:

答案 0 :(得分:0)

我不喜欢搞乱剪贴板,因为用户可能正在使用它......

所以,我使用以下代码完成了这项工作:

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));
}