简体   繁体   English

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

[英]Extract images from word file in C#

I have a problem in image extraction. 我在图像提取方面有问题。 I have written this code to extract all images from word file but this code works for some images means it does save some image files but on the other hand this code does not extract images from Word file. 我已经编写了此代码以从Word文件中提取所有图像,但是此代码适用于某些图像,这意味着它确实保存了一些图像文件,但另一方面,此代码并未从Word文件中提取图像。 I'm using office interop library. 我正在使用Office互操作库。

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

I don't like messing with the Clipboard because the user might be using it... 我不喜欢把剪贴板弄乱,因为用户可能正在使用它...

So, instead I did this using the following code: 因此,我改为使用以下代码执行此操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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