gpt4 book ai didi

wpf - 查找 FlowDocument 中的所有图像

转载 作者:行者123 更新时间:2023-12-04 23:31:54 27 4
gpt4 key购买 nike

由于我对 WPF FlowDocuments 还很陌生,所以我想问一下下面的代码是否正确。它应该将 FlowDocument 中包含的所有图像作为列表返回:

List<Image> FindAllImagesInParagraph(Paragraph paragraph)
{
List<Image> result = null;

foreach (var inline in paragraph.Inlines)
{
var inlineUIContainer = inline as InlineUIContainer;
if (inlineUIContainer != null)
{
var image = inlineUIContainer.Child as Image;

if (image != null)
{
if (result == null)
result = new List<Image>();

result.Add(image);
}
}
}

return result;
}

private List<Image> FindAllImagesInDocument(FlowDocument Document)
{
List<Image> result = new List<Image>();

foreach (var block in Document.Blocks)
{
if (block is Table)
{
var table = block as Table;

foreach (TableRowGroup rowGroup in table.RowGroups)
{
foreach (TableRow row in rowGroup.Rows)
{
foreach (TableCell cell in row.Cells)
{
foreach (var block2 in cell.Blocks)
{
if (block2 is Paragraph)
{
var paragraph = block2 as Paragraph;
var images = FindAllImagesInParagraph(paragraph);
if (images != null)
result.AddRange(images);
}

else if (block2 is BlockUIContainer)
{
var container = block as BlockUIContainer;
if (container.Child is Image)
{
var image = container.Child as Image;
result.Add(image);
}
}
}
}
}
}
}

else if (block is Paragraph)
{
var paragraph = block as Paragraph;
var images = FindAllImagesInParagraph(paragraph);
if (images != null)
result.AddRange(images);
}

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

return result.Count > 0 ? result : null;
}

最佳答案

LINQ 简直太神奇了:

public IEnumerable<Image> FindImages(FlowDocument document)
{
return document.Blocks.SelectMany(FindImages);
}

public IEnumerable<Image> FindImages(Block block)
{
if (block is Table)
{
return ((Table)block).RowGroups
.SelectMany(x => x.Rows)
.SelectMany(x => x.Cells)
.SelectMany(x => x.Blocks)
.SelectMany(FindImages);
}
if (block is Paragraph)
{
return ((Paragraph) block).Inlines
.OfType<InlineUIContainer>()
.Where(x => x.Child is Image)
.Select(x => x.Child as Image);
}
if (block is BlockUIContainer)
{
Image i = ((BlockUIContainer) block).Child as Image;
return i == null
? new List<Image>()
: new List<Image>(new[] {i});
}
throw new InvalidOperationException("Unknown block type: " + block.GetType());
}

关于wpf - 查找 FlowDocument 中的所有图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3899852/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com