首页 文章

在C#中将图像插入RTF文档

提问于
浏览
4

我正在创建一个可以轻松插入图像的RichTextBox子类 . 我提到this question开始,但我无法生成生成的RTF字符串 . 当我尝试设置RTB的SelectedRtf时,它出错"File format is not valid."这是我的代码:

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,但我不想使用该方法 . 有任何想法吗?

谢谢,
贾里德

3 回答

  • 7

    我放弃了尝试手动插入RTF,并决定使用剪贴板方法 . 我从这种解决方案中找到的唯一不利因素是它消灭了剪贴板内容 . 我只是在粘贴图像之前保存它们,然后像这样设置它:

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

    工作得很漂亮 .

  • 3

    RichTextBox不支持PNG,它支持 WMF - but this isn't variant in C# . 此外,RichTextBox支持 BMP format - this is good idea for C# 中的图像,因为Bitmap是标准的.Net类 .

  • 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文件格式,图像 Headers 也以\ pict \ wmetafile8开头 . 尝试将 Headers 更改为该格式,看看它是否有效 .

相关问题