c# Novacode.Picture 到 System.Drawing.Image

c# Novacode.Picture to System.Drawing.Image

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

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

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

还有 this answer 可能是另一个起点。

非常感谢任何帮助。

好的。这就是我最终要做的。感谢 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");
}