【问题标题】:Can't insert a picture into RichTextBox无法在 RichTextBox 中插入图片
【发布时间】:2012-10-08 18:24:47
【问题描述】:

我想在 RichTextBox 中插入图片。我在编码中添加图片。

这是主要代码,添加一张jpg图片:

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+"}";

然后我将“picStr”插入到 rtf 文档中。但是看不到图像。我认为“hexImgStr”可能是错误的。我还以另一种方式生成“hexImgStr”:

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

图片也看不到。它有什么问题。

非常感谢。

【问题讨论】:

    标签: c# winforms image richtextbox rtf


    【解决方案1】:

    这里失败的可能性很高。首先将 RTF 插入正确的位置。真正的问题可能是您生成的确切格式。图像是 RTB 的嵌入式 OLE 对象,它们需要描述对象的元数据标头。 .NET 对此没有任何支持,OLE 嵌入很早以前就走上了渡渡鸟的路。

    我知道可行的一件事是通过剪贴板将图像放入 RTB。像这样:

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

    根据需要调整 SelectionStart 属性以确定图像的插入位置。

    【讨论】:

      【解决方案2】:

      先在picturebox中添加图片,然后在按钮点击事件中添加如下代码

      或者手动添加图片..... image.FromFile("Source");

      Clipboard.SetImage(PictureBox1.Image);
      

      this.RichTextBox1.Paste();

      【讨论】:

        猜你喜欢
        • 2013-06-19
        • 2020-07-02
        • 1970-01-01
        • 1970-01-01
        • 2010-10-07
        • 1970-01-01
        相关资源
        最近更新 更多