C# 二维码的生成

 

nuget 搜索qrcodenet,然后选择下载gma.qrcodenet

 

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
//GenerateQRByQrCodeNet();
pictureBox1.Image = ToQR("http://www.baidu.com");
}

public static Bitmap ToQR(String url)
{
QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.M);
QrCode qrCode = qrEncoder.Encode(url);

GraphicsRenderer render = new GraphicsRenderer(new FixedModuleSize(5, QuietZoneModules.Two), Brushes.Black, Brushes.White);
DrawingSize size = render.SizeCalculator.GetSize(qrCode.Matrix.Width);
Bitmap pic = new Bitmap(size.CodeWidth, size.CodeWidth);
Graphics g = Graphics.FromImage(pic);

render.Draw(g, qrCode.Matrix);

return pic;
}

private void GenerateQRByQrCodeNet()
{
QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);
QrCode qrCode = new QrCode();
qrEncoder.TryEncode("hello this is test application encode", out qrCode);

GraphicsRenderer renderer = new GraphicsRenderer(new FixedModuleSize(5, QuietZoneModules.Two), Brushes.Black, Brushes.White);

string strbaidu = "http://www.baidu.com";
byte[] be = Encoding.Default.GetBytes(strbaidu);

using (MemoryStream ms = new MemoryStream(be))
{
renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, ms);
Image img = Image.FromStream(ms);
pictureBox1.Image = img;
//img.Save("D:/csharp-qrcode-net.png");
}
}
}

posted @ 2019-01-17 14:16  江湖评谈  阅读(370)  评论(0编辑  收藏  举报