【问题标题】:Load image without using system.drawing.image不使用 system.drawing.image 加载图像
【发布时间】:2016-01-25 12:11:07
【问题描述】:

我想加载一个图像流,以便可以使用 PDFsharp 将其转换为 pdf。

以下代码在我的测试/控制台应用程序中有效,但在我使用 ASP.NET Framework 4.6.1 运行的项目中无效。这是因为我使用的是 System.Drawing.Image

System.Drawing.Imaging 命名空间中的类不支持在 Windows 或 ASP.NET 服务中使用。尝试在其中一种应用程序类型中使用这些类可能会产生意想不到的问题,例如服务性能下降和运行时异常。

来源Microsoft

我们如何解决这个问题?我的偏好是将所有内容都保存在内存中。

我在控制台应用程序中的工作代码:

PdfDocument pdfDoc = new PdfDocument();
pdfDoc.Pages.Add(new PdfPage());
MemoryStream MemStream = new MemoryStream(inputStream); // Inputstream as byte[]

Image imgSource = Image.FromStream(MemStream); // This will fail
XImage imgX = XImage.FromGdiPlusImage(imgSource);

XGraphics xgr = XGraphics.FromPdfPage(pdfDoc.Pages[0]);
xgr.DrawImage(imgX, 0, 0);

MemoryStream outputStream = new MemoryStream();
pdfDoc.Save(outputStream, false);
byte[] dataConverted = outputStream.ToArray();
pdfDoc.Close();

return dataConverted;

【问题讨论】:

  • 不能让pdfSharp直接处理图片吗? pdfsharp.net/wiki/Images-sample.ashx
  • 正确,但它只接受图像路径。这正是我想要避免的。编辑:它使用 MigraDoc,这是用于创建带有图像/文本/行/段落等的 pdf。我使用 pdfSharp 仅将图像直接转换为 pdf (pdfsharp.net/Overview.ashx)

标签: c# asp.net .net pdfsharp .net-4.6


【解决方案1】:

只需将流传递给 PDFsharp:

public static XImage FromStream(Stream stream)

对于 PDFsharp 1.50,此方法是公开的。我认为它在 1.3x 版本中不公开。

使用 PDFsharp 的 WPF 构建 - GDI 构建在内部使用 Image.FromStream

【讨论】:

  • 我确实从 NuGet.org 获得了 1.3x 版本。当您选择“包括预发布”时,您可以看到 1.50 版本以及 GDI / WPF 包。谢谢!
猜你喜欢
  • 2013-05-26
  • 1970-01-01
  • 1970-01-01
  • 2020-01-21
  • 2020-06-28
  • 1970-01-01
  • 2013-05-30
  • 1970-01-01
  • 2010-10-12
相关资源
最近更新 更多