![]()
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 ZXing;
namespace QRCode
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
private void btnQRCode_Click(object sender, EventArgs e)
{
string content = txtInputForQR.Text;
Dictionary<EncodeHintType, Object> hints = new Dictionary<EncodeHintType, object>();
hints.Add(EncodeHintType.ERROR_CORRECTION, ZXing.QrCode.Internal.ErrorCorrectionLevel.H);
hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8"); //编码
MultiFormatWriter writer = new MultiFormatWriter();
ZXing.Common.BitMatrix bm = writer.encode(content, ZXing.BarcodeFormat.QR_CODE, 300, 300, hints);
BarcodeWriter barcodeWriter = new BarcodeWriter();
//barcodeWriter.Renderer = new ZXing.Rendering.BitmapRenderer
//{
// Background = Color.FromArgb(242, 241, 250),
// Foreground = Color.FromArgb(46, 51, 57)
//};
barcodeWriter.Renderer = new ZXing.Rendering.BitmapRenderer
{
Background = Color.White,
Foreground = Color.Green
};
System.Drawing.Bitmap bmp = RemoveWhiteMargin(bm, barcodeWriter.Write(bm));//去除边
pictureBox1.Image = bmp;
}
private static Bitmap RemoveWhiteMargin(ZXing.Common.BitMatrix bitMatrix, Bitmap bitmap)
{
//获取参数
int[] rec = bitMatrix.getEnclosingRectangle();
int left = rec[0];
int top = rec[1];
int width = rec[2];
int height = rec[3];
Bitmap newImg = new Bitmap(width, height);
Graphics g = Graphics.FromImage(newImg);
//截取
g.DrawImage(bitmap, 0, 0, new Rectangle(left, top, newImg.Width, newImg.Height), GraphicsUnit.Pixel);
return newImg;
}
private void btnQRDeCode_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "图像文件(*.jpg;*.jpeg;*.gif;*.bmp;*.png)|*.jpg;*.jpeg;*.gif;*.bmp;*.png";
if (openFileDialog1.ShowDialog() != DialogResult.OK)
{
return;
}
Image img = null;
try
{
img = Image.FromFile(openFileDialog1.FileName);
pictureBox1.Image = img;
}
catch (Exception ex)
{
MessageBox.Show("文件格式不正确" + ex.Message);
}
BarcodeReader reader = new BarcodeReader();
reader.Options.CharacterSet = "UTF-8";
Result result = null;
try
{
result = reader.Decode(new Bitmap(img));
}
catch (Exception ex)
{
txtInputForQR.Text = "识别异常" + ex.Message;
}
if (result != null)
{
txtOutputForQR.Text = result.Text;
}
else
{
txtOutputForQR.Text = "未识别出信息!";
}
}
private void btnSave_Click(object sender, EventArgs e)
{
SaveFileDialog sFD = new SaveFileDialog();
sFD.Filter = "保存图片(*.png) |*.png|所有文件(*.*) |*.*";
sFD.DefaultExt = "*.png|*.png";
sFD.AddExtension = true;
if (sFD.ShowDialog() == DialogResult.OK)
{
if (sFD.FileName != "")
{
Bitmap bitmap = (Bitmap)pictureBox1.Image;
bitmap.Save(sFD.FileName, System.Drawing.Imaging.ImageFormat.Png);
}
}
}
}
}
Demo下载