使用QRCodeEncoder生成二维码
1.引用
ThoughtWorks.QRCode.dll
2.步骤
(1)设置QRCodeEncoder对象参数
参数说明:
- QRCodeEncodeMode:三种尺寸:BYTE ,ALPHA_NUMERIC,NUMERIC
- QRCodeScale :大小:L M Q H
- QRCodeVersion :版本:如 8
- QRCodeErrorCorrect:比例:如 4 -
(2)调用Encode方法
- 参数:需要转换成二维码的字符 ,支持中文。如: “4408810820 小明,邯郸” 或者:1234567889
- 返回值:bitmap
3.代码
编码:
private ActionResult CreateCode_Simple(string nr)
{
QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
qrCodeEncoder.QRCodeScale = 4;
qrCodeEncoder.QRCodeVersion = 8;
qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
System.Drawing.Image image = qrCodeEncoder.Encode(nr);
string filename = DateTime.Now.ToString("yyyymmddhhmmssfff").ToString() + ".jpg";
string filepath = Server.MapPath(@"~\Upload") + "\\" + filename;
System.IO.FileStream fs = new System.IO.FileStream(filepath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
image.Save(fs, System.Drawing.Imaging.ImageFormat.Jpeg);
fs.Close();
image.Dispose();
return Content(@"/Upload/" + filename);
}
解码:
/// <summary>
/// 二维码解码
/// </summary>
/// <param name="filePath">图片路径</param>
/// <returns></returns>
public string CodeDecoder(string filePath)
{
if (!System.IO.File.Exists(filePath))
return null;
Bitmap myBitmap = new Bitmap(Image.FromFile(filePath));
QRCodeDecoder decoder = new QRCodeDecoder();
string decodedString = decoder.decode(new QRCodeBitmapImage(myBitmap));
return decodedString;
}
4.说明
生成二维码的字符串如果是链接,(以http://开头),扫描到的机器会直接跳转到这个网址。