4

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

这是我拥有的代码(主要取自 SO 上的另一篇文章):

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");
    }
}

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

或者,更好/更容易使用/记录更好的库的建议也将不胜感激。

4

2 回答 2

4

您无需手动将这些像素数据复制到另一个流。总是更喜欢使用接口提供的方法,即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(...);`
}

演示:

在此处输入图像描述

于 2019-01-07T07:39:53.927 回答
1

并非每个可用的渲染器实现都支持输出条形码下方的内容(fe 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

于 2019-01-10T19:14:12.857 回答