C#二维码生成与解码

【窗体效果图】

C#二维码生成与解码

【程序源代码】

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using com.google.zxing;
using COMMON = com.google.zxing.common; namespace Qcode
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(this.textBox1.Text.Trim()))
{
MessageBox.Show("请输入需要转换的信息!");
}
else
{
string content = this.textBox1.Text;//待编码数据
try
{
int QSize = Int32.Parse(textBox2.Text);//二维码大小
string s = hScrollBar1.Value.ToString("X");//二维码透明度
string q = hScrollBar2.Value.ToString("X");//背景透明度
string Scolor = "0x" + s + textBox3.Text;//二维码颜色
string Qcolor = "0x" + q + textBox4.Text;//背景颜色
COMMON.ByteMatrix byteMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QSize, QSize);
Bitmap bt = toBitmap(byteMatrix, Scolor, Qcolor);
pictureBox1.Image = bt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
} public static Bitmap toBitmap(COMMON.ByteMatrix matrix,string scolor,string qcolor)
{
int width = matrix.Width;
int height = matrix.Height;
Bitmap bmap = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
for (int x = ; x < width; x++)
{
for (int y = ; y < height; y++)
{
bmap.SetPixel(x, y, matrix.get_Renamed(x, y) != - ? ColorTranslator.FromHtml(scolor) : ColorTranslator.FromHtml(qcolor));
}
} return bmap;
} private void button3_Click(object sender, EventArgs e)
{
Image img = pictureBox1.Image;
if (img != null)
{
SaveFileDialog sFD = new SaveFileDialog();
sFD.Filter = "*.png|*.png";
if (sFD.ShowDialog() == DialogResult.OK)
{
Bitmap bmap = new Bitmap(img, img.Width, img.Height);
bmap.Save(sFD.FileName);
MessageBox.Show("保存成功!");
}
}
else
{
MessageBox.Show("您还没有生成二维码!");
}
} private void button2_Click(object sender, EventArgs e)
{
if (this.openFileDialog1.ShowDialog() != DialogResult.OK)
{
return;
}
Bitmap bmap;
try
{
Image img = Image.FromFile(this.openFileDialog1.FileName);
bmap = new Bitmap(img);
if (bmap == null)
{
MessageBox.Show("解码错误,请确保二维码图片已打开!");
return;
}
}
catch
{
MessageBox.Show("解码错误,请确保图片格式正确!");
return;
} LuminanceSource source = new RGBLuminanceSource(bmap, bmap.Width, bmap.Height);
com.google.zxing.BinaryBitmap bitmap = new com.google.zxing.BinaryBitmap(new COMMON.HybridBinarizer(source));
Result result;
try
{
result = new MultiFormatReader().decode(bitmap);
}
catch
{
string str = "解码失败,失败原因可能是:"+"\n";
str += "1.您打开的图片非二维码图片!" + "\n";
str += "2.您打开的二维码图片背景色太深!" + "\n";
str += "3.您打开的二维码图片二维码和背景色太接近!" + "\n";
MessageBox.Show(str);
return;
}
textBox1.Text = result.Text;
} }
}

【引用dll文件】
http://pan.baidu.com/s/1ntNr79v

【关注我的博客】

C#二维码生成与解码

上一篇:如何把.cs文件编译成DLL文件


下一篇:Java二维码生成与解码工具Zxing使用