[英]Extract images from word file in C#
我在圖像提取方面有問題。 我已經編寫了此代碼以從Word文件中提取所有圖像,但是此代碼適用於某些圖像,這意味着它確實保存了一些圖像文件,但另一方面,此代碼並未從Word文件中提取圖像。 我正在使用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();
}
}
}
}
我不喜歡把剪貼板弄亂,因為用戶可能正在使用它...
因此,我改為使用以下代碼執行此操作:
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.