1

我正在使用 Novacode API 读取 .docx 文件,由于无法从 Novacode 图片 (pic) 或图像转换为系统图像,因此无法在文件中创建或显示任何图像到 WinForm 应用程序. 我注意到图片本身的信息非常少,无法获取我能看到的任何像素数据。所以我一直无法利用任何通常的转换思路。

我还查看了 Word 如何在文件中保存图像以及 Novacode 源代码以获取任何提示,但我一无所获。

那么我的问题是有没有办法将 Novacode 图片转换为系统图片,或者我应该使用不同的方法来收集像 OpenXML 这样的图像数据?如果是这样,Novacode 和 OpenXML 会以任何方式发生冲突吗?

还有这个答案可能是另一个开始的地方。

任何帮助深表感谢。

4

1 回答 1

1

好的。这就是我最终做的。感谢gattsbr的建议。仅当您可以按顺序抓取所有图像并为所有图像具有降序名称时,这才有效。

using System.IO.Compression; // Had to add an assembly for this
using Novacode;

// Have to specify to remove ambiguous error from Novacode
Dictionary<string, System.Drawing.Image> images = new Dictionary<string, System.Drawing.Image>();

void LoadTree()
{
    // In case of previous exception
    if(File.Exists("Images.zip")) { File.Delete("Images.zip"); }

    // Allow the file to be open while parsing
    using(FileStream stream = File.Open("Images.docx", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
    {
        using(DocX doc = DocX.Load(stream))
        {
            // Work rest of document

            // Still parse here to get the names of the images
            // Might have to drag and drop images into the file, rather than insert through Word
            foreach(Picture pic in doc.Pictures)
            {
                string name = pic.Description;

                if(null == name) { continue; }

                name = name.Substring(name.LastIndexOf("\\") + 1);
                name = name.Substring(0, name.Length - 4);

                images[name] = null;
            }

            // Save while still open
            doc.SaveAs("Images.zip");
        }
    }

    // Use temp zip directory to extract images
    using(ZipArchive zip = ZipFile.OpenRead("Images.zip"))
    {
        // Gather all image names, in order
        // They're retrieved from the bottom up, so reverse
        string[] keys = images.Keys.OrderByDescending(o => o).Reverse().ToArray();

        for(int i = 1; ; i++)
        {
            // Also had to add an assembly for ZipArchiveEntry
            ZipArchiveEntry entry = zip.GetEntry(String.Format("word/media/image{0}.png", i));

            if(null == entry) { break; }

            Stream stream = entry.Open();

            images[keys[i - 1]] = new Bitmap(stream);
        }
    }

    // Remove temp directory
    File.Delete("Images.zip");
}
于 2016-08-03T22:23:45.393 回答