现如今二维码广泛应用,已经成为了生活中不可或缺的东西;所以我们日常的开发中,也少不了对二维码的生成或者解析。此文讲述一下使用C# 生成和解析二维码
实现功能:
将字符串生成二维码和解析二维码图片
开发环境:
开发工具: Visual Studio 2013
.NET Framework版本:4.5
实现代码:
//需添加zxing.dll和zxing.presentation.dll到自己项目
//需引入命名空间
using ZXing;
using ZXing.Common;
using ZXing.QrCode.Internal;
//生成二维码
private void btnGenerate_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(textBox1.Text))
{
MessageBox.Show("请输入要生成的文本信息");
return;
}
BarcodeWriter barCodeWriter = new BarcodeWriter();
barCodeWriter.Format = BarcodeFormat.QR_CODE;
barCodeWriter.Options.Hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
barCodeWriter.Options.Height = 230;
barCodeWriter.Options.Width = 230;
BitMatrix bm = barCodeWriter.Encode(textBox1.Text);
Bitmap img = barCodeWriter.Write(bm);
pictureBox1.Image = img;
}
//解析二维码
private void btnAnalysis_Click(object sender, EventArgs e)
{
if (pictureBox1.Image == null)
{
MessageBox.Show("请先复制图片到图片框");
return;
}
BarcodeReader reader = new BarcodeReader();
reader.Options.CharacterSet = "UTF-8";
Result result = reader.Decode((Bitmap)pictureBox1.Image);
textBox1.Text = result.Text;
}
//获取剪切板中的图片
private Image CopyImage()
{
try
{
Image image = null;
IDataObject iData = Clipboard.GetDataObject();
if (iData.GetDataPresent(DataFormats.FileDrop))
{
object obj = iData.GetData(DataFormats.FileDrop);
image = Image.FromFile((obj as string[])[0].ToString());
}
else if (iData.GetDataPresent(DataFormats.Bitmap))
{
object obj = iData.GetData(DataFormats.Bitmap);
image = obj as Image;
}
return image;
}
catch { return null; }
}
//给予pictureBox1焦点
private void pictureBox1_Click(object sender, EventArgs e)
{
pictureBox1.Focus();
}
//ctrl+v复制到pictureBox1
private void pictureBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.Control && e.KeyCode == Keys.V)
{
pictureBox1.Image = CopyImage();
}
}
实现效果: