将图像插入在C#中的RTF文档 [英] Insert an image into RTF document in C#
问题描述
我创建一个RichTextBox子类,它可以很容易地插入图像。我提到这个问题开始,但我不能得到的生成RTF字符串工作。当我尝试设置RTB的SelectedRtf,它的错误用文件格式不正确。这是我的code:
内部空隙InsertImage(图片IMG)
{
字符串str = @{\ PICT \ pngblip \ picw24 \ pich24+ imageToHex(IMG)+};
this.SelectedRtf =海峡; //此行引发异常
}
私人字符串imageToHex(图片IMG)
{
MemoryStream的毫秒=新的MemoryStream();
img.Save(MS,ImageFormat.Png);
字节[]字节= ms.ToArray();
字符串十六进制= BitConverter.ToString(字节);
返回hex.Replace( - ,);
}
我见过的工作是我想要做的,但使用wmetafiles的例子,但我想preFER不要使用该方法。任何想法?
谢谢,
贾里德
我放弃了试图手动插入RTF,并决定使用剪贴板办法
内部空隙InsertImage(图片IMG)
{
IDataObject的OBJ = Clipboard.GetDataObject();
Clipboard.Clear();
Clipboard.SetImage(IMG);
this.Paste();
Clipboard.Clear();
Clipboard.SetDataObject(OBJ);
}
美丽的作品。
I am creating a RichTextBox subclass that can insert images easily. I referred to this question to start, but I can't get the generated RTF string to work. When I try to set the SelectedRtf of the RTB, it errors out with "File format is not valid." Here is my code:
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("-", "");
}
I've seen working examples of what I'm trying to do, but using wmetafiles, but I would prefer not to use that method. Any ideas?
Thanks,
Jared
I gave up trying to insert the RTF manually, and decided to use the clipboard approach. The only detriment I could find from this type of solution was that it wiped out the clipboard contents. I simply saved them before I paste the image, then set it back like so:
internal void InsertImage(Image img)
{
IDataObject obj = Clipboard.GetDataObject();
Clipboard.Clear();
Clipboard.SetImage(img);
this.Paste();
Clipboard.Clear();
Clipboard.SetDataObject(obj);
}
Works beautifully.
这篇关于将图像插入在C#中的RTF文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!