2010-08-26 43 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();