先下载ZXing.dll
using ZXing;
using ZXing.QrCode;
/// <summary>
/// 生成二维码
/// </summary>
/// <param name="text">二维码内容</param>
/// <param name="width">宽度</param>
/// <param name="height">高度</param>
/// <returns></returns>
public static Bitmap GenQrCodePic(string text, int width, int height)
{
BarcodeWriter writer = new BarcodeWriter();
writer.Format = BarcodeFormat.QR_CODE;
QrCodeEncodingOptions options = new QrCodeEncodingOptions()
{
DisableECI = true,//设置内容编码
CharacterSet = "UTF-8", //设置二维码的宽度和高度
Width = width,
Height = height,
Margin = 1//设置二维码的边距,单位不是固定像素
};
writer.Options = options;
Bitmap map = writer.Write(text);
return map;
}
/// <summary>
/// 生成带Logo的二维码
/// </summary>
/// <param name="text">内容</param>
/// <param name="width">宽度</param>
/// <param name="height">高度</param>
public static Bitmap GenQrCodeLogoPic(string text, string logoPath, int width, int height)
{
Bitmap logo = new Bitmap(logoPath);
//计算插入图片的大小和位置
int middleW = Math.Min((int)(width / 4), logo.Width);
int middleH = Math.Min((int)(height / 4), logo.Height);
int middleL = (width - middleW) / 2;
int middleT = (height - middleH) / 2;
构造二维码写码器
Bitmap bmpimg = GenQrCodePic(text, width, height);
using (Graphics g = Graphics.FromImage(bmpimg))
{
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.DrawImage(bmpimg, 0, 0, width, height);
//白底将二维码插入图片
g.FillRectangle(Brushes.White, middleL, middleT, middleW, middleH);
g.DrawImage(logo, middleL, middleT, middleW, middleH);
}
return bmpimg;
}