PDFsharp 图像到 XImage

PDFsharp image to XImage

我在 ASP.NET MVC 应用程序中创建了条形码作为图像。

BarcodeLib.Barcode barcode = new BarcodeLib.Barcode()                   
{                        
    IncludeLabel = false,
    Alignment = AlignmentPositions.LEFT,
    Width = element.BarcodeWidth,
    Height = element.BarcodeHeight,
    RotateFlipType = RotateFlipType.RotateNoneFlipNone,
    BackColor = Color.Transparent,
    ForeColor = Color.Black,
    ImageFormat = System.Drawing.Imaging.ImageFormat.Png
 };

这将使用 BarcodeLib 创建条形码。
如何将其转换为 PDFsharp 的 XImage?

Image img = barcode.Encode(TYPE.CODE128, "123456789");
gfx.DrawImage(xImage, 0, 0, 100, 100);

如果您使用 PDFsharp 的 GDI 构建,那么您可以调用 XImage.FromImage 方法。

使用任何版本的 PDFsharp,您都可以将 PNG 图像写入 MemoryStream,然后从该 MemoryStream 获取 XImage。

这样解决的:

Image img = barcode.Encode(TYPE.CODE128, Name); // this is the image

MemoryStream strm = new MemoryStream();
img.Save(strm, System.Drawing.Imaging.ImageFormat.Png);

XImage xfoto = XImage.FromStream(strm);

此外, 如果你知道图像路径,你可以使用它

XImage xImage = XImage.FromFile(imagePath)

实际上方法在.net core 版本中已经改变。它以 Func 作为参数。请注意:这是.net core的非官方版本。

XImage xImage = XImage.FromStream(() => new MemoryStream(yourByte[]));