我试图通过单击按钮将图像插入RichTextBox
。
我提到了这篇文章-How can I insert an image into a RichTextBox?,并制作了源代码
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog f = new OpenFileDialog();
f.Filter = "BMP (*.bmp)|*.bmp|JPEG (*.jpg, *.jpeg, *.jpe, *.jfif)|*.jpg;*.jpeg;*.jpe;*.jfif|GIF (*.gif)|*.gif|PNG (*.png)|*.png|All files|*.bmp;*.jpg;*.jpeg;*.jpe;*.jfif;*.gif;*.png";
if (f.ShowDialog() == DialogResult.OK)
{
// Get type of the file
string typeOfFile = "";
Stack<char> typeParse = new Stack<char>();
int pointer = f.FileName.Length - 1
while (pointer > 0 && f.FileName[pointer] != '.')
typeParse.Push(f.FileName[pointer--]);
while (typeParse.Count > 0)
typeOfFile += typeParse.Pop();
typeOfFile = typeOfFile.ToLower();
// Convert Image to byte[]
Image image = Image.FromFile(f.FileName);
MemoryStream ms = new MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
// Insert the image data in RichTextBox which is converted to hex from byte[]
// by using BitConverter.ToString(ms.ToArray();
StringBuilder imageRTF = new StringBuilder();
imageRTF.Append(@"{\pict\" + typeOfFile + @"blip\picw" + image.Width + @"\pich" + image.Height);
imageRTF.Append(@"\picwgoal" + image.Width + @"\pichgoal" + image.Height);
imageRTF.Append(@" " + BitConverter.ToString(ms.ToArray()) + @"}");
string rtf1 = richTextBox1.Rtf.Trim().TrimEnd('}');
string rtf2 = imageRTF.ToString();
richTextBox1.Rtf = rtf1 + rtf2;
}
}
但是当我执行并打开png文件时,在RichTextBox
中仅插入了一个换行符。
怎么了?