简体   繁体   中英

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

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.

You can use System.Drawing.Bitmap to do this. Add reference to CoreCompat.System.Drawing nuget package (it's in beta) and then use this code:

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

As far as I know ImageSharp is not released yet. I recommended CoreCompact based on this answer .

You can use ImageSharp to load up the raw pixel data (assuming pixelData.Pixels is a byte[] containing raw rgba32 formatted pixel data). Instead of using Image.Load<Rgba32>(data, width, height) you should be using Image.LoadPixelData<Rgba32>(data)

So you final loading code would be:

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

Basically the Image.Load<Rgba32>(data) api is for loading up encoded data ie png, jpg etc formatted data. Where as the Image.LoadPixelData<Rgba32>(data) api is for loading up raw pixel data into the image object for later processing/saving.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM