using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using ZXing;
using ZXing.Common;
using ZXing.OneD;
using ZXing.QrCode;
using ZXing.QrCode.Internal;
namespace Utility.Tools
{
public class BarcodeHelper
{
static readonly string prefix = "data:image/png;base64,";
public static Bitmap GetCodeBar(string txt, int width, int height, bool hideCode = false)
{
Code128EncodingOptions options = new Code128EncodingOptions()
{
Width = width,
Height = height,
Margin = 0,
PureBarcode = hideCode,
ForceCodesetB = true,
GS1Format = false
};
BarcodeWriter writer = new BarcodeWriter
{
Format = BarcodeFormat.CODE_128,
Options = options,
};
try
{
Bitmap map = writer.Write(txt);
return map;
}
catch (Exception e)
{
var msg = e.Message;
return null;
}
}
///
/// 获取一维码的Base64内容【png格式】
///
///
///
///
///
///
public static string GetCodeBarBase64(string txt, int width, int height, bool hideCode = false)
{
Bitmap map = GetCodeBar(txt, width, height, hideCode);
if (map == null)
{
return string.Empty;
}
MemoryStream stream = new MemoryStream();
try
{
map.Save(stream, ImageFormat.Png);
string re = $"{prefix}{Convert.ToBase64String(stream.ToArray())}";
return re;
}
catch (Exception)
{
return string.Empty;
}
finally
{
map.Dispose();
stream.Dispose();
}
}
///
/// 获取二维码QR
///
///
///
///
///
public static Bitmap GetQrCode(string txt, int width, int height)
{
QrCodeEncodingOptions options = new QrCodeEncodingOptions()
{
DisableECI = true,//设置内容编码
CharacterSet = "UTF-8", //设置二维码的宽度和高度
Width = width,
Height = height,
ErrorCorrection = ErrorCorrectionLevel.H,
Margin = 0//设置二维码的边距,单位不是固定像素
};
BarcodeWriter writer = new BarcodeWriter
{
Format = BarcodeFormat.QR_CODE,
Options = options
};
try
{
Bitmap map = writer.Write(txt);
return map;
}
catch (Exception)
{
return null;
}
}
///
/// 获取二维码QR的Base64内容【png格式】
///
///
///
///
///
public static string GetQrCodeBase64(string txt, int width, int height)
{
Bitmap map = GetQrCode(txt, width, height);
if (map == null)
{
return string.Empty;
}
MemoryStream stream = new MemoryStream();
try
{
map.Save(stream, ImageFormat.Png);
string re = $"{prefix}{Convert.ToBase64String(stream.ToArray())}";
return re;
}
catch (Exception)
{
return string.Empty;
}
finally
{
map.Dispose();
stream.Dispose();
}
}
///
/// 获取识别一维码或二维码的结果
///
///
///
public static string GetDecode(string base64)
{
string re = string.Empty;
var bts = Convert.FromBase64String(base64);
MemoryStream stream = new MemoryStream(bts);
var map = (Bitmap)Image.FromStream(stream);
//
var reader = new BarcodeReader();
try
{
var result = reader.Decode(map);
if (result != null)
{
re = $"{result.BarcodeFormat}:{result.Text}";
}
return re;
}
catch (Exception)
{
return re;
}
finally
{
stream.Dispose();
map.Dispose();
}
}
}
}