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.