2010-08-26 64 views
2

我想将图片插入RichTextBox。我在编码中添加图片。无法将图片插入RichTextBox

这是主要的代码,添加一个JPG图片:

MemoryStream memoryStream = new MemoryStream(); 
img.Save(memoryStream,System.Drawing.Imaging.ImageFormat.Jpeg); 
byte[] bytes = memoryStream.ToArray(); 
String width = img.Width.ToString(); 
String height = img.Height.ToString(); 
String hexImgStr=BitConverter.ToString(bytes, 0).Replace("-",""); 
String [email protected]"{\pict\jpegblip\picw"[email protected]"\pich"+height+ 
       @"\picwgoal"[email protected]"\pichgoal"+height+" "+hexImgStr+"}"; 

然后,我将 “picStr” 的RTF文档。但形象无法看到。我认为“hexImgStr”可能是错误的。我还以另一种方式生成“hexImgStr”:

FileStream fs = new FileStream(imgPath,FileMode.Open); 
BinaryReader br=new BinaryReader(fs); 
//byte[] bytes=new byte[fs.Length]; 
String hexImgStr=""; 
for (long i = 0; i < fs.Length; i++) 
{ 
    //bytes[i] = br.ReadByte(); 
    hexImgStr +=Convert.ToString(br.ReadByte(),16); 
} 

图像也无法看到。它出什么问题了。

非常感谢。

回答

2

这里很有可能失败。它首先将RTF插入正确的位置。真正的问题可能是您生成的确切格式。图像是RTB嵌入的OLE对象,它们需要描述对象的元数据头。在.NET中对此没有任何支持,很久以前,OLE嵌入就成为了dodo的方式。

我知道的一件事情是,通过剪贴板将图像插入RTB。像这样:

private void button1_Click(object sender, EventArgs e) { 
     using (var img = Image.FromFile("c:\\screenshot.png")) { 
      Clipboard.SetImage(img); 
      richTextBox1.Paste(); 
     } 
    } 

根据需要调整SelectionStart属性以确定图像的插入位置。

1

首先添加图片到PictureBox的,然后添加以下代码按钮点击事件

内部或手动添加图片..... image.FromFile(“源”);

Clipboard.SetImage(PictureBox1.Image); 

this.RichTextBox1.Paste();