【问题标题】:Insert an image into RTF document in C#在 C# 中将图像插入 RTF 文档
【发布时间】:2011-07-11 12:32:31
【问题描述】:

我正在创建一个可以轻松插入图像的 RichTextBox 子类。我提到 this question 开始,但我无法让生成的 RTF 字符串工作。当我尝试设置 RTB 的 SelectedRtf 时,出现“文件格式无效”错误。这是我的代码:

internal void InsertImage(Image img)
{
    string str = @"{\pict\pngblip\picw24\pich24 " + imageToHex(img) + "}";

    this.SelectedRtf = str;    // This line throws the exception
}

private string imageToHex(Image img)
{
    MemoryStream ms = new MemoryStream();
    img.Save(ms, ImageFormat.Png);

    byte[] bytes = ms.ToArray();

    string hex = BitConverter.ToString(bytes);
    return hex.Replace("-", "");
}

我已经看到了我正在尝试做的工作示例,但使用的是 wmetafiles,但我不想使用这种方法。有什么想法吗?

谢谢,
贾里德

【问题讨论】:

    标签: c# .net richtextbox rtf


    【解决方案1】:

    RichTextBox 不支持 PNG,它支持 WMF - 但这不是 C# 中的变体。此外,RichTextBox 支持 BMP 格式的图像 - 这对 C# 来说是个好主意,因为 Bitmap 是标准的 .Net 类。

    【讨论】:

      【解决方案2】:

      我放弃了手动插入 RTF 的尝试,决定使用剪贴板方法。我能从这种类型的解决方案中发现的唯一不利因素是它清除了剪贴板内容。我只是在粘贴图像之前保存了它们,然后像​​这样设置它:

      internal void InsertImage(Image img)
      {
          IDataObject obj = Clipboard.GetDataObject();
          Clipboard.Clear();
      
          Clipboard.SetImage(img);
          this.Paste();
      
          Clipboard.Clear();
          Clipboard.SetDataObject(obj);
      }
      

      效果很好。

      【讨论】:

      • 插入图像工作正常,但在 Win8 x64 中,剪贴板内容无法恢复。在 XP 中它可以工作。
      【解决方案3】:

      也许这是一种幼稚的方法,但我只是使用写字板将 PNG 插入到 RTF 文档中。下面是第一块:

      {\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 Calibri;}}
      {\*\generator Msftedit 5.41.21.2510;}\viewkind4\uc1\pard\sa200\sl276\slmult1\lang9\f0\fs22 testing\par
      \par
      \pard\sa200\sl240\slmult1{\pict\wmetafile8\picw27940\pich16378\picwgoal8640\pichgoal5070 
      0100090000035af60e00000031f60e0000000400000003010800050000000b0200000000050000
      000c026b022004030000001e000400000007010400040000000701040031f60e00410b2000cc00
      6b022004000000006b0220040000000028000000200400006b020000010018000000000020ec1d
      0000000000000000000000000000000000ffffffffffffffffffffffffffffffffffffffffffff
      ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
      fffffffffffffffffffffffffffffffffff
      

      如您所见,即使使用 PNG 文件格式,图像标题也以 \pict\wmetafile8 开头。尝试将您的标题更改为该格式,看看它是否有效。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-12-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-14
        • 1970-01-01
        • 2011-07-27
        相关资源
        最近更新 更多