将图像从word文档转换为位图对象

时间:2011-02-02 02:39:55

标签: c# .net image interop ms-word

根据项目要求,我们需要将图像从word文档转换为位图对象。为此,我们尝试将inlineshape对象从Microsoft.Office.Interop.Word dll转换为位图。但无法获得成功,将剪贴板对象设为null。请找到我们尝试过的代码,如下所示;

using System.Drawing;
using Microsoft.Office.Interop.Word;
namespace WordApp1
{
    class Program
    {
        static void Main(string[] args)
        {
           Application wordApp = (Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
           Documents documents = wordApp.Documents;

           Document d = null;
           foreach (Document document in documents)
           {
              if (document.ActiveWindow.Caption.Contains("{Word document name}"))
              {
                 d = document;
              }
           }

           foreach (InlineShape shape in d.InlineShapes)
           {
              shape.Range.Select();
              d.ActiveWindow.Selection.Range.CopyAsPicture();
              System.Windows.Forms.IDataObject dobj = System.Windows.Forms.Clipboard.GetDataObject();  //Getting clipboard object as null
              if(dobj.GetDataPresent(typeof(System.Drawing.Bitmap)))
              {
                 Bitmap bmp;
                 System.IO.MemoryStream ms = new System.IO.MemoryStream();
                 bmp = (Bitmap)dobj.GetData(typeof(System.Drawing.Bitmap));
              }
            }
        }        
     }
 }

是否有人致力于将单词图像转换为位图?如果您可以指导我们如何继续将图像从word文档转换为位图对象,那将是非常有用的。

3 个答案:

答案 0 :(得分:2)

此帖子已解决:https://stackoverflow.com/a/7937590/1071212 这是STAThread的一个问题:

Thread thread = new Thread([Method]);
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();

答案 1 :(得分:0)

试试这个。

foreach (InlineShape shape in d.InlineShapes)             
{ 
    if (shape != null)
    {
        shape.Range.Select(); 
        d.ActiveWindow.Selection.Copy();
        Bitmap bitmap = new Bitmap(Clipboard.GetImage());
    }
}

答案 2 :(得分:0)

有两个剪贴板。

通常我们会使用System.Windows.Forms.Clipboard,但很糟糕。

请改用System.Windows.Clipboard,只需将PresentationCore添加到参考文献中。

(在我的例子中,C:\ Program Files \ Reference Assemblies \ Microsoft \ Framework.NETFramework \ v4.0 \ Profile \ Client \ PresentationCore.dll)