【问题标题】:Adding System.Drawing.Image to FixedDocument将 System.Drawing.Image 添加到 FixedDocument
【发布时间】:2014-06-23 07:12:43
【问题描述】:

我有 10 个System.Drawing.Image。我需要将它们添加到FixedDocument。我尝试了下面的代码,并生成了固定文档,所有 10 页仅包含第一张图片。

FixedDocument doc = new FixedDocument();
BitmapSource[] bmaps = new BitmapSource[10];
System.Drawing.Image[] drawingimages = //I have System.Drawing.Image in a array
for (int i = 0; i < 10; i++)
{

    Page currentPage = this.Pages[i];
    System.Drawing.Image im = drawingimages[i];
    im.Save(i + ".png");
    Stream ms = new MemoryStream();
    im.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
    var decoder = BitmapDecoder.Create(ms, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnDemand);
    ImageSource imgsource = decoder.Frames[0];

    bmaps[i] = imgsource as BitmapSource;
}
foreach (BitmapSource b in bmaps)
{
    PageContent page = new PageContent();
    FixedPage fixedPage = CreateOneFixedPage(b);
    ((IAddChild)page).AddChild(fixedPage);
    doc.Pages.Add(page);
}

CreateOneFixedPage 的方法

private FixedPage CreateOneFixedPage(BitmapSource img)
{
    FixedPage f = new FixedPage();
    Image anImage = new Image();
    anImage.BeginInit();
    anImage.Source = img;
    anImage.EndInit();

    f.Children.Add(anImage);
    return f;
}

当我尝试将System.Drawing.Image 保存到本地磁盘时,所有 10 个图像都正确保存。 我的代码有什么错误?

【问题讨论】:

  • 如果在 BitmapDecoder.Create() 中将 BitmapCacheOption 更改为 BitmapCacheOption.OnLoad 会发生什么?
  • 并且不需要在 Image 控件上调用 BeginInit() 和 EndInit()。
  • @Clemens: 都试过了,,, 但问题仍然存在

标签: c# wpf image fixeddocument


【解决方案1】:

也许不是问题的答案,但至少下面的代码显示了一个最小的工作示例。它将 Sample Pictures 文件夹中的所有图像加载到 System.Drawing.Bitmap 对象列表中。然后它将所有列表元素转换为 ImageSource 并将每个元素添加到 FixedDocment 页面。

请注意它不会调用图像控件上的BeginInit()EndInit()。它还设置 PageContent 的 Child 属性,而不是调用 IAddChild.AddChild()

var bitmaps = new List<System.Drawing.Bitmap>();

foreach (var file in Directory.EnumerateFiles(
    @"C:\Users\Public\Pictures\Sample Pictures", "*.jpg"))
{
    bitmaps.Add(new System.Drawing.Bitmap(file));
}

foreach (var bitmap in bitmaps)
{
    ImageSource imageSource;

    using (var stream = new MemoryStream())
    {
        bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
        stream.Position = 0;
        imageSource = BitmapFrame.Create(stream,
            BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
    }

    var page = new FixedPage();
    page.Children.Add(new Image { Source = imageSource });

    doc.Pages.Add(new PageContent { Child = page });
}

【讨论】:

  • 感谢@Clemens ...这也无法绘制所有图像。只画第一页 10 次
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-05
  • 2023-04-02
  • 2022-11-18
相关资源
最近更新 更多