使用 ZXing.net 生成条形码

Generate barcode with ZXing.net

我正在尝试使用 ZXing.NET 为 dot net core asp.net 应用程序生成条形码。我不知道如何显示带有条形码的文本,文档似乎真的非常缺乏。有谁知道如何让它发挥作用吗?

这是我的代码(大部分取自 SO 上的另一个 post):

BarcodeWriterPixelData writer = new BarcodeWriterPixelData()
{
    Format = BarcodeFormat.CODE_128,
    Options = new EncodingOptions
    {
        Height = 400,
        Width = 800,
        PureBarcode = false, // this should indicate that the text should be displayed, in theory. Makes no difference, though.
        Margin = 10
    }
};

var pixelData = writer.Write("test text");

using (var bitmap = new Bitmap(pixelData.Width, pixelData.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb))
{
    using (var ms = new System.IO.MemoryStream())
    {
        var bitmapData = bitmap.LockBits(new Rectangle(0, 0, pixelData.Width, pixelData.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
        try
        {
            System.Runtime.InteropServices.Marshal.Copy(pixelData.Pixels, 0, bitmapData.Scan0, pixelData.Pixels.Length);
        }
        finally
        {
            bitmap.UnlockBits(bitmapData);
        }

        bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
        return File(ms.ToArray(), "image/jpeg");
    }
}

这给我一个条形码,但没有内容。

或者,better/easier 对 use/better-documented 图书馆的建议也将不胜感激。

您不需要手动将这些像素数据复制到另一个流。总是喜欢使用接口提供的方法,即Save()方法。

public void YourActionMethod()
{
    BarcodeWriter writer = new BarcodeWriter(){
        Format = BarcodeFormat.CODE_128,
        Options = new EncodingOptions {
            Height = 400,
            Width = 800,
            PureBarcode = false,
            Margin = 10,
        },
    };

    var bitmap = writer.Write("test text");
    bitmap.Save(HttpContext.Response.Body,System.Drawing.Imaging.ImageFormat.Png);
    return; // there's no need to return a `FileContentResult` by `File(...);`
}

演示:

并非所有可用的渲染器实现都支持条形码下方内容的输出(f.e。PixelData 渲染器不支持)。 您应该为不同的图像库使用一种特定的实现。 例如,以下绑定提供了一个支持内容输出的渲染器(和特定的 BarcodeWriter): https://www.nuget.org/packages/ZXing.Net.Bindings.CoreCompat.System.Drawing https://www.nuget.org/packages/ZXing.Net.Bindings.Windows.Compatibility https://www.nuget.org/packages/ZXing.Net.Bindings.ZKWeb.System.Drawing https://www.nuget.org/packages/ZXing.Net.Bindings.SkiaSharp