C# / WPF: Richtextbox: Find all Images

我与影子孤独终老i 提交于 2019-12-17 19:52:38

问题


i want a chat with inline images. The richtextbox 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?

Thank you :)


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/4404516/c-sharp-wpf-richtextbox-find-all-images

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!