代码中添加引用:using ThoughtWorks.QRCode.Codec;
public void CreateImg()
{
string content = "";//二维码内容
Bitmap image = CreatBitmapImg(content); //生成二维码图片
//保存图片到本地
string fileName = Guid.NewGuid().ToString().Replace("-", "") + ".png";
//图片保存地址,需要绝对路径
string filePath = HttpContext.Current.Server.MapPath("/Image/" + fileName);
image.Save(filePath, System.Drawing.Imaging.ImageFormat.Png);
//***************************************************************************
//在一般处理程序中或者Api中生成,需要返回
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
string base64 = Convert.ToBase64String(ms.ToArray());
//返回imageUrl,前台直接绑定到图片控件
var imageUrl = "data:image/png;base64," + base64;
}
/// <summary>
/// 生成二维码图片
/// </summary>
/// <param name="content">包含内容</param>
/// <returns></returns>
public Bitmap CreatBitmapImg(string content)
{
System.Drawing.Bitmap image;
//创建二维码生成类
QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
//设置编码模式
qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
//设置编码版本
qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.H;
//设置编码测量度
qrCodeEncoder.QRCodeScale = 3;
//设置编码版本
qrCodeEncoder.QRCodeVersion = 8;
image = qrCodeEncoder.Encode(content, Encoding.UTF8);
return image;
}