C# 如何将图像插入 RichTextBox?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/542850/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I insert an image into a RichTextBox?
提问by Daniel LeCheminant
Most of the examples I see say to put it on the clipboard and use paste, but that doesn't seem to be very good because it overwrites the clipboard.
我看到的大多数示例都说要将其放在剪贴板上并使用粘贴,但这似乎不是很好,因为它会覆盖剪贴板。
I did see one methodthat manually put the image into the RTF using a pinvoke to convert the image to a wmf. Is this the best way? Is there any more straightforward thing I can do?
我确实看到了一种使用 pinvoke 将图像手动放入 RTF 以将图像转换为 wmf 的方法。这是最好的方法吗?我还能做更直接的事情吗?
采纳答案by Sylverdrag
The most straightforward way would be to modify the RTF code to insert the picture yourself.
最直接的方法是修改 RTF 代码以自己插入图片。
In RTF, a picture is defined like this:
在 RTF 中,图片是这样定义的:
'{' \pict (brdr? & shading? & picttype & pictsize & metafileinfo?) data '}' A question mark indicates the control word is optional. "data" is simply the content of the file in hex format. If you want to use binary, use the \bin control word.
'{' \pict (brdr? & shading? & picttype & pictsize & metafileinfo?) data '}' 问号表示控制字是可选的。“数据”只是十六进制格式的文件内容。如果要使用二进制,请使用 \bin 控制字。
For instance:
例如:
{\pict\pngblip\picw10449\pich3280\picwgoal5924\pichgoal1860 hex data}
{\pict\pngblip\picw10449\pich3280\picwgoal5924\pichgoal1860\bin binary data}
\pict = starts a picture group, \pngblip = png picture \picwX = width of the picture (X is the pixel value) \pichX = height of the picture \picwgoalX = desired width of the picture in twips
\pict = 开始一个图片组,\pngblip = png 图片 \picwX = 图片的宽度(X 是像素值) \pichX = 图片的高度 \picwgoalX = 图片所需的宽度,以缇为单位
So, to insert a picture, you just need to open your picture, convert the data to hex, load these data into a string and add the RTF codes around it to define a RTF picture. Now, you have a self contained string with picture data which you can insert in the RTF code of a document. Don't forget the closing "}"
因此,要插入图片,您只需要打开图片,将数据转换为十六进制,将这些数据加载到字符串中并在其周围添加 RTF 代码以定义 RTF 图片。现在,您有一个包含图片数据的自包含字符串,您可以将其插入到文档的 RTF 代码中。不要忘记结束“}”
Next, you get the RTF code from your RichTextBox (rtbBox.Rtf), insert the picture at the proper location, and set the code of rtbBox.Rtf
接下来,从你的 RichTextBox (rtbBox.Rtf) 中获取 RTF 代码,将图片插入适当的位置,并设置 rtbBox.Rtf 的代码
One issue you may run into is that .NET RTB does not have a very good support of the RTF standard.
您可能会遇到的一个问题是 .NET RTB 对 RTF 标准没有很好的支持。
I have just made a small application* which allows you to quickly test some RTF code inside a RTB and see how it handles it. You can download it here: RTB tester(http://your-translations.com/toys).
我刚刚制作了一个小应用程序*,它允许您快速测试 RTB 中的一些 RTF 代码并查看它如何处理它。您可以在此处下载: RTB 测试器( http://your-translations.com/toys)。
You can paste some RTF content (from Word, for instance) into the left RTF box and click on the "Show RTF codes" to display the RTF codes in the right RTF box, or you can paste RTF code in the right RTB and click on "Apply RTF codes" to see the results on the left hand side.
您可以将一些 RTF 内容(例如来自 Word)粘贴到左侧 RTF 框中,然后单击“显示 RTF 代码”以在右侧 RTF 框中显示 RTF 代码,或者您可以将 RTF 代码粘贴到右侧 RTF 中并单击在“应用 RTF 代码”上查看左侧的结果。
You can of course edit the codes as you like, which makes it quite convenient for testing whether or not the RichTextBox supports the commands you need, or learn how to use the RTF control words.
您当然可以随意编辑代码,这对于测试 RichTextBox 是否支持您需要的命令或学习如何使用 RTF 控制字非常方便。
You can download a full specification for RTF online.
您可以在线下载 RTF 的完整规范。
NB It's just a little thing I slapped together in 5 minutes, so I didn't implement file open or save, drag and drop, or other civilized stuff.
NB这只是我在5分钟内拍打在一起的小东西,所以我没有实现文件打开或保存,拖放或其他文明的东西。
回答by Sesh
Here is what I do to hack the rich text control:
这是我如何破解富文本控件:
Insert the required image in wordpad or MS-WORD. Save the file as 'rtf'. Open the rtf file in notepad to see the raw rtf code. Copy the required tags & stuff to the 'rtf' property of your Rich Text Box (append to existing text).
在写字板或 MS-WORD 中插入所需的图像。将文件另存为“rtf”。在记事本中打开 rtf 文件以查看原始 rtf 代码。将所需的标签和内容复制到富文本框的“rtf”属性(附加到现有文本)。
There is some trial and error involved but works.
涉及一些试验和错误,但有效。
With C#, I use place holder StringBuilder objects with the necessary rtf code. Then I just append the image path.
在 C# 中,我使用占位符 StringBuilder 对象和必要的 rtf 代码。然后我只是附加图像路径。
This is a workaround for not having to learn the RTF syntax.
这是一种不必学习 RTF 语法的解决方法。
回答by Joel Lucsy
If you were in C++, the way to do it is thru OLE. More specifically, if you search Google for ImageDataObject it will show C++ code how to insert a HBITMAP into the RTF Control. One link is here.
如果您使用的是 C++,则可以通过 OLE 来实现。更具体地说,如果您在 Google 上搜索 ImageDataObject,它将显示 C++ 代码如何将 HBITMAP 插入到 RTF 控件中。一个链接在这里。
Now, how this translates into .Net code, I don't know. I currently don't have the time to work thru the details.
现在,这如何转化为 .Net 代码,我不知道。我目前没有时间处理细节。
回答by Joel Lucsy
private void toolStripButton1_Click(object sender, EventArgs e)
{
FileDialog fDialog = new OpenFileDialog();
fDialog.CheckFileExists = true;
fDialog.CheckPathExists = true;
fDialog.RestoreDirectory = true;
fDialog.Title = "Choose file to import";
if (fDialog.ShowDialog() == DialogResult.OK)
{
string lstrFile = fDialog.FileName;
Bitmap myBitmap = new Bitmap(lstrFile);
// Copy the bitmap to the clipboard.
Clipboard.SetDataObject(myBitmap);
DataFormats.Format format = DataFormats.GetFormat(DataFormats.Bitmap);
// After verifying that the data can be pasted, paste
if(top==true && this.rtTop.CanPaste(format))
{
rtTop.Paste(format);
}
if (btmLeft == true && this.rtBottomLeft.CanPaste(format))
{
rtBottomLeft.Paste(format);
}
if (btmCenter == true && this.rtBottomCenter.CanPaste(format))
{
rtBottomCenter.Paste(format);
}
if (btmRight == true && this.rtBottomRight.CanPaste(format))
{
rtBottomRight.Paste(format);
}
}
}
回答by Bibek Dahal
I use the following code to first get the data from clipboard, save it in memory, set the image in clipboard, paste it in Rich Text Box and finally restore the data in Clipboard.
我使用以下代码首先从剪贴板中获取数据,将其保存在内存中,在剪贴板中设置图像,将其粘贴到富文本框中,最后在剪贴板中恢复数据。
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
OpenFileDialog1.Filter = "All files |*.*"
OpenFileDialog1.Multiselect = True
Dim orgdata = Clipboard.GetDataObject
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
For Each fname As String In OpenFileDialog1.FileNames
Dim img As Image = Image.FromFile(fname)
Clipboard.SetImage(img)
RichTextBox1.Paste()
Next
End If
Clipboard.SetDataObject(orgdata)
End Sub
The OpenFileDailog1, RichTextBox1 and Button1 are Open File Dialog, Rich Text Box and button controls respectively.
OpenFileDailog1、RichTextBox1 和 Button1 分别是打开文件对话框、富文本框和按钮控件。
回答by Hymanocurly0074
I was also looking for something for this same task and found this ->
我也在为同样的任务寻找一些东西并找到了这个 ->
http://sourceforge.net/projects/netrtfwriter/
http://sourceforge.net/projects/netrtfwriter/
You can generate any type of RTF text that you would want and then use it however you wish. Very well structured example which will auto sense the image type being used (jpg/jpeg/png etc) and worked for the image files I have been using. If you are in a hurry then this is a great RTF generator!
您可以生成您想要的任何类型的 RTF 文本,然后随意使用它。结构非常好的示例,它将自动检测正在使用的图像类型(jpg/jpeg/png 等)并为我一直使用的图像文件工作。如果您赶时间,那么这是一个很棒的 RTF 生成器!
回答by Larryrl
All I did was make a small pictureBox control in c# and made sure it was hidden behind another object big enough to hide it. Then I made a button to insert a picture, and it loaded the pictureBox with the image then it puts it in the richTextBox then it clears the pictureBox control.
我所做的只是在 c# 中制作了一个小的图片框控件,并确保它隐藏在另一个足够大的对象后面以将其隐藏。然后我做了一个按钮来插入一张图片,它用图片加载了图片框,然后把它放在 RichTextBox 中,然后它清除了图片框控件。
Here is the code.
这是代码。
private void InsertPicture_Click(object sender, EventArgs e)
{
{
if (openFileDialog4.ShowDialog() == DialogResult.OK)
{
// Show the Open File dialog. If the user clicks OK, load the
// picture that the user chose.
pictureBox2.Load(openFileDialog4.FileName);
Clipboard.SetImage(pictureBox2.Image);
pictureBox2.Image = null;
this.richTextBox1.Paste();
}
}
}
回答by SandraTinch
My own version that I posted in a new thread, apparently I should have searched and posted it here. Anyway, using the clipboard again, very easy.
我在一个新线程中发布的我自己的版本,显然我应该在这里搜索并发布它。无论如何,再次使用剪贴板,非常容易。
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "Images |*.bmp;*.jpg;*.png;*.gif;*.ico";
openFileDialog1.Multiselect = false;
openFileDialog1.FileName = "";
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
Image img = Image.FromFile(openFileDialog1.FileName);
Clipboard.SetImage(img);
richTextBox1.Paste();
richTextBox1.Focus();
}
else
{
richTextBox1.Focus();
}
}
}
回答by Sourcephy
Several hours surfing for solution to insert image without loosing quality and fixed the gray background with transparent image/png
冲浪几个小时以解决在不降低质量的情况下插入图像并使用透明图像/png修复灰色背景
// assuming the image is in your Resources
var img = Resources.ImageWithTransparentBckgrnd;
var g = Graphics.FromImage(img);
using (var ms = new MemoryStream())
{
img.Save(ms, ImageFormat.Png);
IntPtr ipHdc = g.GetHdc();
Metafile mf = new Metafile(ms, ipHdc);
g = Graphics.FromImage(mf);
g.FillEllipse(Brushes.White, 0, 0, 16, 16); // size you want to fill in
g.Dispose();
mf.Save(ms, ImageFormat.Png);
IDataObject dataObject = new DataObject();
dataObject.SetData("PNG", false, ms);
Clipboard.SetDataObject(dataObject, false);
richTextBox1.Paste();
SendKeys.Send("{RIGHT}");
richTextBox1.Focus();
}