开发者

Find all images in a RichTextBox

I want a chat with inline images.

The rich开发者_高级运维textbox is good, because I can place images in it, but I want to send the text / images separate.

  • first: send the text (and place a image-placeholder in the text).
  • second: send the image and replace it with the placeholder.

For that I need to remove all images in the richtextbox (and send them separate). But how can I find the images?

And BTW: Is it possible to rescale the image dependent on the width of the richtextbox?


To find all images in a RichTextBox, you need to traverse through all Paragraphs and its Inlines; and then you can do whatever you need with the image. For example, the following code will increase the size (by 1 pixel) of all images inside a RichTextBox.

public static void ResizeRtbImages(RichTextBox rtb)
{
    foreach (Block block in rtb.Blocks)
    {
        if (block is Paragraph)
        {
            Paragraph paragraph = (Paragraph)block;
            foreach (Inline inline in paragraph.Inlines)
            {
                if (inline is InlineUIContainer)
                {
                    InlineUIContainer uiContainer = (InlineUIContainer)inline;
                    if (uiContainer.Child is Image)
                    {
                        Image image = (Image)uiContainer.Child;
                        image.Width = image.ActualWidth + 1;
                        image.Height = image.ActualHeight + 1;
                    }
                }
            }
        }
    }
}


Adding to Prabu Arumugam's answer, the Block can also be a BlockUIContainer with an Image, so you would need:

else if (block is BlockUIContainer)
{
    var container = (BlockUIContainer)block;
    if (container.Child is Image)
    {
        Image image = (Image)container.Child;
        // ...
    }
} 

I'd also prefer Linq syntax for compactness, maybe something like this:

public static void ResizeRtbImages(RichTextBox rtb)
{
    IEnumerable<Image> images = rtb.Document.Blocks.OfType<BlockUIContainer>()
            .Select(c => c.Child).OfType<Image>()
        .Union(rtb.Documents.Blocks.OfType<Paragraph>()
            .SelectMany(pg => pg.Inlines.OfType<InlineUIContainer>())
            .Select(inline => inline.Child).OfType<Image>()
        );
    foreach (var image in images)
    {
        // resize
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜