gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:08:52 25 4
gpt4 key购买 nike

我正在创建一个可以轻松插入图像的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com