2011-03-08 103 views
4

我正在創建一個可以輕鬆插入圖像的RichTextBox子類。我提到this question開始,但我不能讓生成的RTF字符串工作。當我嘗試設置RTB的SelectedRtf時,它以「文件格式無效」出錯。這裏是我的代碼:在C#中插入圖像到RTF文檔中

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("-", ""); 
} 

我見過的工作是什麼,我試圖做的,但使用wmetafiles的例子,但我寧願不要使用該方法。有任何想法嗎?

感謝,
賈裏德

回答

7

我放棄了試圖手動插入RTF,並決定使用剪貼板的方法。我能從這種解決方案中找到的唯一不利之處是它將剪貼板內容刪除。我只是救了他們之前,我粘貼的圖像,然後將其設置回像這樣:

internal void InsertImage(Image img) 
{ 
    IDataObject obj = Clipboard.GetDataObject(); 
    Clipboard.Clear(); 

    Clipboard.SetImage(img); 
    this.Paste(); 

    Clipboard.Clear(); 
    Clipboard.SetDataObject(obj); 
} 

精美的作品。

+0

插入圖片可以正常工作,但剪貼板內容在Win8 x64中無法恢復。在XP中,它的作品。 – AlexP11223 2013-04-11 06:49:00

+0

不能恢復XP 32中的剪貼板... – 2014-10-08 09:30:26

2

也許這是一個幼稚的做法,但我只是用寫字板插入PNG成RTF文檔。下面是第一大塊:

{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 Calibri;}} 
{\*\generator Msftedit 5.41.21.2510;}\viewkind4\uc1\pard\sa200\sl276\slmult1\lang9\f0\fs22 testing\par 
\par 
\pard\sa200\sl240\slmult1{\pict\wmetafile8\picw27940\pich16378\picwgoal8640\pichgoal5070 
0100090000035af60e00000031f60e0000000400000003010800050000000b0200000000050000 
000c026b022004030000001e000400000007010400040000000701040031f60e00410b2000cc00 
6b022004000000006b0220040000000028000000200400006b020000010018000000000020ec1d 
0000000000000000000000000000000000ffffffffffffffffffffffffffffffffffffffffffff 
ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 
fffffffffffffffffffffffffffffffffff 

正如你可以看到,即使與PNG文件格式,圖像標頭\ PICT \ wmetafile8開始。嘗試將您的標題更改爲該格式並查看它是否有效。

3

RichTextBox不支持PNG,它支持WMF - 但這不是C#中的變體。此外,RichTextBox支持BMP格式的圖像 - 這對於C#來說是個好主意,因爲Bitmap是標準的.Net類。