Insert image into RTF document in C #

I am creating a subclass of RichTextBox that can easily insert images. I mentioned this question , but I cannot get the generated RTF string to work. When I try to set SelectedRtf to RTB, it erroneously displays "File format is invalid." 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 saw working examples of what I'm trying to do, but using wmetafiles, but I would prefer not to use this method. Any ideas?

Thanks,
Jared

+4
source share
3 answers

I gave up trying to paste RTF manually and decided to use the approach in the clipboard. The only damage that I could find in this solution was that it destroyed the contents of the clipboard. I just saved them before inserting the image, and then set it like this:

 internal void InsertImage(Image img) { IDataObject obj = Clipboard.GetDataObject(); Clipboard.Clear(); Clipboard.SetImage(img); this.Paste(); Clipboard.Clear(); Clipboard.SetDataObject(obj); } 

It works great.

+7
source

RichTextBox does not support PNG, it supports WMF, but this is not an option in C # . RichTextBox also supports BMP images - this is a good idea for C # , since Bitmap is a standard .Net class.

+3
source

This may be a naive approach, but I just used WordPad to embed PNG in an RTF document. Below is the first snippet:

 {\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 

As you can see, even with the PNG file format, the image header starts with \ pict \ wmetafile8. Try changing the title to this format and see if it works.

+2
source

Source: https://habr.com/ru/post/1342918/


All Articles