用到外部一個DLL文件(ThoughtWorks.QRCode.dll),看效果
生成截圖
識別截圖
生成二維碼后右鍵菜單可以保存二維碼圖片,然后可以到識別模式下進行識別,當然生成后可以用手機掃描識別出來,或者用手機直接掃描以上兩張圖也能看到識別后的結果。
使用方法,在解決方案中引用上面那個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;
}
}
}