views:

28

answers:

1

I want to insert a picture into a RichTextBox. I add the picture in coding.

This is the major code, adding a jpg image:

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 picStr=@"{\pict\jpegblip\picw"+width+@"\pich"+height+
              @"\picwgoal"+width+@"\pichgoal"+height+" "+hexImgStr+"}";

Then I insert the "picStr" to the rtf document. But the image can't be seen. I thought "hexImgStr" maybe wrong. I also generate the "hexImgStr" in another way:

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);
}

The image can't be seen either. What's wrong with it.

Thanks a lot.

+1  A: 

There's a high probability of failure here. It starts with inserting the RTF in the right place. The true problem is likely to be the exact format you generate. Images are embedded OLE objects for RTB, they need a metadata header that describes the object. There is no support whatsoever for this in .NET, OLE embedding went the way of the dodo a long time ago.

One thing I know that works is to get an image into an RTB through the clipboard. Like this:

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

Adjust the SelectionStart property as necessary to determine where the image gets inserted.

Hans Passant