C#生成二维码
现在的社会上,二维码随处可见,需求量也越来越大,在很多项目的需求中都存在生成二维码的需求
其实二维码的生成并不难,使用C#可以很好的读写二维码(本例使用VS2013开发)
不过首先我们还需要一个库zing.dll,可以到这里下载:http://zxingnet.codeplex.com/
1、新建项目,创建窗体
往一个form控件里拖一个pictureBox存放二维码,一个文本框存放二维码信息,一个按钮响应生成动作
2、把zxing.dll引用到项目中,然后写后台代码
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using ZXing.Common; using ZXing; namespace 二维码生成器 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } /* * 函数名:buttonGenerate_Click * 作用:生成二维码 * 参数:object sender, EventArgs e * 返回:void */ private void buttonGenerate_Click(object sender, EventArgs e) { // 获取输入信息 string info = textBoxSet.Text.ToString(); // 生成二维码 Bitmap result = null; // 结果图片 int HEIGHT = 200; // 图片高度 int WIDTH = 200; // 图片宽度 try { BarcodeWriter barCodeWriter = new BarcodeWriter(); barCodeWriter.Format = BarcodeFormat.QR_CODE; // 二维码有很多标准,这里可以设定 barCodeWriter.Options.Hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8"); barCodeWriter.Options.Hints.Add(EncodeHintType.ERROR_CORRECTION, ZXing.QrCode.Internal.ErrorCorrectionLevel.H); barCodeWriter.Options.Height = HEIGHT; barCodeWriter.Options.Width = WIDTH; barCodeWriter.Options.Margin = 0; ZXing.Common.BitMatrix bm = barCodeWriter.Encode(info); result = barCodeWriter.Write(bm); // 显示出来 this.pictureBoxCode.Image = result; // 保存为图片文件 string filePath = System.AppDomain.CurrentDomain.BaseDirectory + "..\\QR_CODE_" + info.Substring(0, 10) + ".jpg"; result.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg); } catch (Exception ex) { //异常输出 MessageBox.Show("二维码生成过程出错!"); } } } }
3、测试,生成的二维码保存到了图片文件中,二维码的.jpg文件在项目的.exe文件的同目录下,程序中可以规定位置