Generate EAN Barcode Using ZXing.Net and get a base64 string

时间:2017-05-16 09:18:34

标签: c# .net asp.net-core barcode zxing

I would like to generate EAN 13 Barcode using ZXing.NET in ASP.NET and convert it to the base64 string.

I have a problem how to convert BarcodeWriterPixelData which I'm getting from:

BarcodeWriterPixelData writer = new BarcodeWriterPixelData()
{
   Format = BarcodeFormat.EAN_13
};
var pixelData = writer.Write(barcodeModel.BarcodeNumber);

I was trying by using ImageSharp

var base64String = string.Empty;
using (Image<Rgba32> image = Image.Load<Rgba32>(pixelData.Pixels))
{
    base64String = image.ToBase64String();
}

But it's not working.

2 个答案:

答案 0 :(得分:4)

您可以使用System.Drawing.Bitmap执行此操作。添加对CoreCompat.System.Drawing nuget包的引用(它处于测试阶段),然后使用此代码:

BarcodeWriterPixelData writer = new BarcodeWriterPixelData()
{
    Format = BarcodeFormat.EAN_13
};
var pixelData = writer.Write(barcodeModel.BarcodeNumber);

using (var bitmap = new System.Drawing.Bitmap(pixelData.Width, pixelData.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb))
{
    using (var ms = new System.IO.MemoryStream())
    {
        var bitmapData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, pixelData.Width, pixelData.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
        try
        {
             // we assume that the row stride of the bitmap is aligned to 4 byte multiplied by the width of the image   
            System.Runtime.InteropServices.Marshal.Copy(pixelData.Pixels, 0, bitmapData.Scan0, pixelData.Pixels.Length);
        }
        finally
        {
            bitmap.UnlockBits(bitmapData);
        }

        // PNG or JPEG or whatever you want
        bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        var base64str = Convert.ToBase64String(ms.ToArray());
    }
}

据我所知ImageSharp尚未发布。我推荐基于this answer的CoreCompact。

答案 1 :(得分:1)

您可以使用ImageSharp加载原始像素数据(假设pixelData.Pixels是包含原始rgba32格式像素数据的byte [])。您应该使用Image.Load<Rgba32>(data, width, height)

而不是Image.LoadPixelData<Rgba32>(data)

所以你最后的加载代码是:

var base64String = string.Empty;
using (Image<Rgba32> image = Image.LoadPixelData<Rgba32>(pixelData.Pixels, width, height))
{
    base64String = image.ToBase64String(ImageFormats.Png);
}

基本上Image.Load<Rgba32>(data) api用于加载编码数据,即png,jpg等格式化数据。其中Image.LoadPixelData<Rgba32>(data) api用于将原始像素数据加载到图像对象中以供以后处理/保存。