最近搞了下从word中提取图片,之前都没接触过c#,开始还是有点小担心,怕不会弄,任务在身,不得不搞,发现c#还是很好用的。^_^
接下来说说word提取图片的事。c#提供了Microsoft.Office.Interop.Word,可以操作word文档,提取出图片,当然不仅仅是提取图片,从操作word可以看出,可以干很多事了,要做什么,自己需要什么就做什么。使用这个玩意有点不好的是,你必须安装office软件。
下面贴出来测试用的代码片段,所测试的是计算出文档中的图片数量和提取里面的某一张图片。代码请看:
protected int Extract_image(string command, string word_path, string save_image_path = "c:\\",int page=1)
{
path = save_image_path;
object missing = Type.Missing;
object FileName = word_path;
object readOnly = true;
m_word = new Application();//readOnly
m_word.Documents.Open(ref FileName,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
if ("A" == command)
{
int counts = m_word.ActiveDocument.InlineShapes.Count;
object save = false;
m_word.Quit(ref save, ref missing, ref missing);
m_word = null;
return counts;
}
if("B" == command)
{
try
{
// for (i = 1; i <= m_word.ActiveDocument.InlineShapes.Count; i++)
// {
if (page > m_word.ActiveDocument.InlineShapes.Count)
{
m_i = m_word.ActiveDocument.InlineShapes.Count;
}
else
m_i = page;
Thread thread = new Thread(save);
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
thread.Abort();
// }
}
finally
{
object save = false;
// m_word.Documents.Close();
m_word.Quit(ref save, ref missing, ref missing);
m_word = null;
}
}
return -1;
}
protected void save()
{
InlineShape inlineShape = m_word.ActiveDocument.InlineShapes[m_i];
inlineShape.Select();
m_word.Selection.Copy();
Computer computer = new Computer();
Image img = computer.Clipboard.GetImage();
if (computer.Clipboard.GetDataObject() != null)
{
System.Windows.Forms.IDataObject data = computer.Clipboard.GetDataObject();
if (data.GetDataPresent(System.Windows.Forms.DataFormats.Bitmap))
{
Image image = (Image)data.GetData(System.Windows.Forms.DataFormats.Bitmap, true);
string name = path;
name += "/";
name += Convert.ToString(m_i);
name += ".png";
image.Save(name, System.Drawing.Imaging.ImageFormat.Png);
}
}
}
这个使用起还是可以,考虑要安装office软件,这个有时候是有点不方便,我们可以使用开源的NPOI来做这件事,在这就不贴出来代码了,自己查找。