C#生成和识别二维码

用到外部一个DLL文件(ThoughtWorks.QRCode.dll),看效果

C#生成和识别二维码

生成截图

C#生成和识别二维码

识别截图

生成二维码后右键菜单可以保存二维码图片,然后可以到识别模式下进行识别,当然生成后可以用手机扫描识别出来,或者用手机直接扫描以上两张图也能看到识别后的结果。

使用方法,在解决方案中引用上面那个dll文件,引入命名空间

using ThoughtWorks.QRCode.Codec;
using ThoughtWorks.QRCode.Codec.Data;

看完整的生成二维码代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using ThoughtWorks.QRCode.Codec;
using ThoughtWorks.QRCode.Codec.Data;
namespace 二维码
{
public partial class UC_To : UserControl
{
public UC_To()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text.Trim() != "")
{
string enCodeString = textBox1.Text;
QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
pictureBox1.Image = qrCodeEncoder.Encode(enCodeString, Encoding.UTF8);
}
//else
//MessageBox.Show("请输入内容");
} private void 保存图片ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (pictureBox1.Image != null)
{
SaveFileDialog s = new SaveFileDialog();
s.Title = "保存二维码图片";
s.Filter = "图片文件(*.jpg)|*.jpg";
if(s.ShowDialog()==DialogResult.OK)
try
{
pictureBox1.Image.Save(s.FileName,System.Drawing.Imaging.ImageFormat.Jpeg);
MessageBox.Show("保存成功");
}
catch { MessageBox.Show("保存失败"); }
}
}
}
}

看完整的识别二维码的代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using ThoughtWorks.QRCode.Codec;
using ThoughtWorks.QRCode.Codec.Data;
namespace 二维码
{
public partial class UC_From : UserControl
{
public UC_From()
{
InitializeComponent();
}
string filepath = "";
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog p = new OpenFileDialog();
p.Title = "请选择二维码文件";
p.Filter = "图片文件(*.jpg)|*.jpg";
p.Multiselect = false;
if (p.ShowDialog() == DialogResult.OK)
{
filepath = p.FileName;
System.Threading.Thread t = new System.Threading.Thread(ss);
t.IsBackground = true;
t.Start();
}
}
private void ss()
{
if (filepath != "")
{
string tt = "";
try
{
Invoke((EventHandler)delegate
{
button1.Enabled = false;
button1.Text = "Waiting!";
pictureBox1.Image = new Bitmap(filepath);
});
//pictureBox1.Size = new Size(new Bitmap(filepath).Size.Width, new Bitmap(filepath).Size.Height);
QRCodeDecoder qrDecoder = new QRCodeDecoder();
string txtMsg = qrDecoder.decode(new QRCodeBitmapImage(new Bitmap(pictureBox1.Image)), Encoding.UTF8);
tt = txtMsg;
}
catch { tt = "识别失败"; }
Invoke((EventHandler)delegate
{
textBox1.Text = tt;
button1.Enabled = true;
button1.Text = "识别";
});
}
System.Threading.Thread.CurrentThread.Abort();
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true;
}
}
}
上一篇:SpringBoot导入excle文件数据


下一篇:cdnbest区域自定义配置里添加防xss攻击配置