Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert an image into RTF document in C#

I am creating a RichTextBox subclass that can insert images easily. I referred to this question to start, but I can't get the generated RTF string to work. When I try to set the SelectedRtf of the RTB, it errors out with "File format is not valid." Here is my code:

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

I've seen working examples of what I'm trying to do, but using wmetafiles, but I would prefer not to use that method. Any ideas?

Thanks,
Jared

like image 431
Jared Avatar asked Dec 10 '22 10:12

Jared


2 Answers

I gave up trying to insert the RTF manually, and decided to use the clipboard approach. The only detriment I could find from this type of solution was that it wiped out the clipboard contents. I simply saved them before I paste the image, then set it back like so:

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

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

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

Works beautifully.

like image 166
Jared Avatar answered Dec 11 '22 22:12

Jared


RichTextBox doesn't support PNG, it supports WMF - but this isn't variant in C#. Also the RichTextBox supports images in BMP format - this is good idea for C#, because the Bitmap is standard .Net class.

like image 39
Maxim Sautin Avatar answered Dec 11 '22 22:12

Maxim Sautin