c# - 在 C# 中将图像插入到 RTF 文档中

标签 c# .net richtextbox rtf

我正在创建一个可以轻松插入图像的 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,但我不想使用该方法。有什么想法吗?

谢谢,
贾里德

最佳答案

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

internal void InsertImage(Image img)
{
    IDataObject obj = Clipboard.GetDataObject();
    Clipboard.Clear();

    Clipboard.SetImage(img);
    this.Paste();

    Clipboard.Clear();
    Clipboard.SetDataObject(obj);
}

工作精美。

关于c# - 在 C# 中将图像插入到 RTF 文档中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5239832/

相关文章:

c# - 使用 C# 与 NSUrlSession 的 HTTP POST 多部分表单数据

c# 检测换行

c# - 添加新文本时保留之前的行

python - 在 Python 中显示大量格式化文本

c# - OpenXML SDK 返回 CellValue 的数字而不是单元格文本

c# - 在声明中存储字符串列表 (System.Security.Claims)

c# - 在Unity中动态改变物体的速度

c# - 在 C# 中调整 JPEG 图像的大小会降低其分辨率

.net - .NET中的增量压缩

javascript - 在浏览器应用程序和 .net Windows 应用程序之间进行通信