1.winfrom 中生成二维码。
private void FrmTest_Load(object sender, EventArgs e)
{
string code="二维码内容";
GenByZXingNet(code);
}
/// <summary>
/// 生成二维码
/// </summary>
/// <param name="msg">二维码信息</param>
/// <returns>图片</returns>
private Bitmap GenByZXingNet(string msg)
{
BarcodeWriter writer = new BarcodeWriter();
writer.Format = BarcodeFormat.QR_CODE;
writer.Options.Hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8");//编码问题
writer.Options.Hints.Add(EncodeHintType.ERROR_CORRECTION, ZXing.QrCode.Internal.ErrorCorrectionLevel.H);
const int codeSizeInPixels = 200; //设置图片长宽
writer.Options.Height = writer.Options.Width = codeSizeInPixels;
writer.Options.Margin = 0;//设置边框
ZXing.Common.BitMatrix bm = writer.Encode(msg);
Bitmap img = writer.Write(bm);
picQRCode.Image = img;
return img;
}
2.web版二维码生成(生成图片保存到本地,在给地址到img)
protected void Button1_Click(object sender, EventArgs e)
{
//获取文本框输入值
string str = TextBox1.Text;
//获取路径
string path = System.Web.HttpContext.Current.Server.MapPath("images");
string file = path + "\\code.png";
QRCodeHelper qdh=new QRCodeHelper();
if (qdh.ToQRCode(str, file))
{
Image1.ImageUrl = "images/code.png";
Label1.Text = "生成成功";
}
else
Label1.Text = "生成失败";
}
/// <summary>
/// 生成二维码
/// </summary>
/// <param name="str">生成二维码内容</param>
/// <param name="strPath">二维码存放路径</param>
/// <returns>是否成功 true:成功 false:失败</returns>
public bool ToQRCode(string str, string strPath)
{
//创建二维码生成类
QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
//设置编码模式
qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
//设置编码错误纠正
qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
设置编码版本
qrCodeEncoder.QRCodeVersion = 1;
//设置编码测量度
qrCodeEncoder.QRCodeScale = 7;
//生成二维码图片
Bitmap image = qrCodeEncoder.Encode(str, Encoding.Default);
//将image保存到filename
image.Save(strPath);
return true;
}