本文内容在《C#二维码生成与解码》的基础上增加了纠错级别和Logo图标加入,增加了二维码的功能。关于透明度在这里没有单独显现,因为在颜色里面就已经包含,颜色值由8位8进制构成,最前面的两位就是控制透明度的,后面的6位分为对应红绿蓝的值。

【窗体效果图】

【程序源代码】

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;
using ZXing.QrCode.Internal;
using System.IO; namespace ErWeiMa
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
cbocorrection.SelectedIndex = ;
} /// <summary>获取标志图像路径</summary>
private void btnLogo_Click(object sender, EventArgs e)
{
var dlg = new OpenFileDialog()
{
Filter = "图片文件|*.png;*.bmp;*.dib;*.jpg;*.jpeg;*.jpe;*.jfif;*.tif;*.tiff|所有文件|*.*",
Multiselect = false
};
if (dlg.ShowDialog() ==DialogResult.OK)
this.txtLogoFile.Text = dlg.FileName;
} /// <summary>生成二维码图片</summary>
private void btnGen_Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(this.txtMessage.Text))
{
MessageBox.Show("编码用的内容字符串不能为空。", "操作错误",MessageBoxButtons.OK,MessageBoxIcon.Error);
return;
} this.imgQrcode.Image = null; try
{
// 纠错级别
var errCorrLvl = ErrorCorrectionLevel.M;
var corrRatio = 0.15;
switch (this.cbocorrection.SelectedIndex)
{
case : errCorrLvl = ErrorCorrectionLevel.L; corrRatio = 0.07; break;
case : errCorrLvl = ErrorCorrectionLevel.M; corrRatio = 0.15; break;
case : errCorrLvl = ErrorCorrectionLevel.Q; corrRatio = 0.25; break;
case : errCorrLvl = ErrorCorrectionLevel.H; corrRatio = 0.30; break;
} int Qsize = Int32.Parse(textBox1.Text);
if(Qsize==)
Qsize=(int)this.imgQrcode.Width;
// 生成 QR Code 位图
var hints = new Dictionary<EncodeHintType, object>();
hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
hints.Add(EncodeHintType.ERROR_CORRECTION, errCorrLvl);
var matrix = new MultiFormatWriter().encode(this.txtMessage.Text, BarcodeFormat.QR_CODE,Qsize ,Qsize, hints);
var bitmap = new Bitmap(matrix.Width, matrix.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
var deepColor = ColorTranslator.FromHtml("0xff000000");
var lightColor = ColorTranslator.FromHtml("0xffffffff");
if (!String.IsNullOrWhiteSpace(this.txtDeepColor.Text))
deepColor = ColorTranslator.FromHtml("0x" + this.txtDeepColor.Text.TrimStart('#'));
if (!String.IsNullOrWhiteSpace(this.txtLightColor.Text))
lightColor = ColorTranslator.FromHtml("0x" + this.txtLightColor.Text.TrimStart('#'));
for (int x = ; x < matrix.Width; x++)
for (int y = ; y < matrix.Height; y++)
bitmap.SetPixel(x, y, matrix[x, y] ? deepColor : lightColor); // 添加标志
if (!String.IsNullOrWhiteSpace(this.txtLogoFile.Text))
{
if (File.Exists(this.txtLogoFile.Text))
{
var logo = new Bitmap(this.txtLogoFile.Text);
var ratio = (double)(logo.Width * logo.Height) / (double)(bitmap.Width * bitmap.Height);
if (ratio > corrRatio * 0.6) // 标志图片大小最大只能占到最大容错面积的60%以保证图片高可读性
{
MessageBox.Show(String.Format("在当前指定的纠错级别下,标志图片大小最大只能占到二维码图片面积的 {0:P1}。", corrRatio * 0.6), "操作错误",MessageBoxButtons.OK,MessageBoxIcon.Error);
return;
} CreateQRCodeBitmapWithPortrait(bitmap, logo);
}
else
{
var dlgResult = MessageBox.Show("指定的标志图片文件不存在!\r\n是否忽略标志图片继续生成?", "警告",MessageBoxButtons.YesNo,MessageBoxIcon.Warning);
if (dlgResult == DialogResult.OK) return;
}
}
this.imgQrcode.Image = bitmap;
}
catch (Exception ex)
{
MessageBox.Show(String.Format("生成二维码图片时出错。\r\n错误类型:{0}\r\n错误信息:{1}", ex.GetType(), ex.Message), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
} } /// <summary>在二维码位图上绘制标志。</summary>
private void CreateQRCodeBitmapWithPortrait(Bitmap qrCode, Bitmap logo)
{
Graphics g = Graphics.FromImage(qrCode);
int qsize = Int32.Parse(textBox1.Text);
// 设置头像要显示的位置,即居中显示
int rectX = (qsize- logo.Width) / ;
int rectY = (qsize - logo.Height) / ;
g.DrawImage(logo, rectX, rectY); g.Dispose();
} /// <summary>保存二维码图片 </summary>
private void btnSave_Click(object sender, EventArgs e)
{
Image img = imgQrcode.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 btnRead_Click(object sender, EventArgs e)
{
var dlg = new OpenFileDialog()
{
Filter = "图片文件|*.png;*.bmp;*.dib;*.jpg;*.jpeg;*.jpe;*.jfif;*.tif;*.tiff|所有文件|*.*",
Multiselect = false
};
if (dlg.ShowDialog() ==DialogResult.OK)
{
// 采用先将图片文件内容读入字节数组然后再通过该数组创建图像实例是为了读取图片后图片文件不再会被文件访问锁锁定
byte[] bytes = null;
using (var stream = File.Open(dlg.FileName, FileMode.Open))
using (BinaryReader reader = new BinaryReader(stream))
{
var fileInfo = new FileInfo(dlg.FileName);
bytes = reader.ReadBytes(unchecked((int)fileInfo.Length));
reader.Close();
} try
{
MemoryStream ms = new MemoryStream(bytes);
imgQrcode.Image = new Bitmap(ms);
}
catch (Exception ex)
{
this.imgQrcode = null;
MessageBox.Show(String.Format("读取图片信息时出错,可能图片是不认识的图像格式。\r\n错误类型:{0}\r\n错误信息:{1}", ex.GetType(), ex.Message), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
} private void btnAnalysis_Click(object sender, EventArgs e)
{
var image = imgQrcode.Image;
if (image == null)
{
MessageBox.Show("二维码图片空白,还没读取二维码图片。", "操作错误", MessageBoxButtons.OK, MessageBoxIcon.Stop);
return;
} this.txtMessage.Text = String.Empty;
this.lblQ.Text = "(空)"; Bitmap bitmap;
bitmap = new Bitmap(image); try
{
LuminanceSource source = new BitmapLuminanceSource(bitmap);
/*
* 在二值化方面,GlobalHistogramBinarizer 提供了比较基础的二值化方法,而 HybridBinarizer 则算是高级的算法,建议要机器性能比较好才使用。
* HybridBinarizer 在识别对比度比较低的图片就是比 GlobalHistogramBinarizer 要差;
* HybridBinarizer 在光照均匀的情况下,效果比 GlobalHistogramBinarizer 优。
*/
// var binarizer = new ZXing.Common.HybridBinarizer(luminance);
var binarizer = new ZXing.Common.GlobalHistogramBinarizer(source);
var binBitmap = new BinaryBitmap(binarizer);
var hints = new Dictionary<DecodeHintType, object>();
hints.Add(DecodeHintType.CHARACTER_SET, "UTF-8");
var result = new MultiFormatReader().decode(binBitmap, hints);
if (result == null)
{
MessageBox.Show("无法正确解析图片。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
} this.txtMessage.Text = result.Text;
this.lblQ.Text = result.BarcodeFormat.ToString();
}
catch (Exception ex)
{
MessageBox.Show(String.Format("解析图片时出错。\r\n错误类型:{0}\r\n错误信息:{1}", ex.GetType(), ex.Message), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

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

【关注我的博客】

C#二维码生成与解码(二)的更多相关文章

  1. Java二维码生成与解码

      基于google zxing 的Java二维码生成与解码   一.添加Maven依赖(解码时需要上传二维码图片,所以需要依赖文件上传包) <!-- google二维码工具 --> &l ...

  2. HTML-DEV-ToolLink(常用的在线字符串编解码、代码压缩、美化、JSON格式化、正则表达式、时间转换工具、二维码生成与解码等工具,支持在线搜索和Chrome插件。)

    HTML-DEV-ToolLink:https://github.com/easonjim/HTML-DEV-ToolLink 常用的在线字符串编解码.代码压缩.美化.JSON格式化.正则表达式.时间 ...

  3. jquery二维码生成插件_二维码生成器

    jquery二维码生成插件_二维码生成器 下载地址:jquery生成二维码.rar

  4. C#实现二维码生成与解码

    前几天公司内部分享了一个关于二维码的例子,觉得挺好玩的,但没有提供完整的源码.有时候看到一个好玩的东西,总想自己Demo一个,于是抽空就自己研究了一下. 一.二维码的原理 工欲善其事,必先利其器.要生 ...

  5. Java二维码生成与解码工具Zxing使用

    Zxing是Google研发的一款非常好用的开放源代码的二维码生成工具,目前源码托管在github上,源码地址: https://github.com/zxing/zxing 可以看到Zxing库有很 ...

  6. 转【微信小程序 四】二维码生成/扫描二维码

    原文:https://blog.csdn.net/xbw12138/article/details/75213274 前端 二维码生成 二维码要求:每分钟刷新一次,模拟了个鸡肋,添加了个按分钟显示的时 ...

  7. C#二维码生成与解码

    [窗体效果图] [程序源代码] using System; using System.Collections.Generic; using System.ComponentModel; using S ...

  8. 主攻ASP.NET.4.5 MVC4.0之重生:二维码生成和谷歌二维码

    使用ThoughtWorks.QRCode.Codec 效果图 using ThoughtWorks.QRCode.Codec; 非原创代码 public void code(string id) { ...

  9. simple go web application & 二维码生成 & 打包部署

    go语言简易web应用 & 二维码生成及解码 & 打包部署 转载请注明出处: https://www.cnblogs.com/funnyzpc/p/10801476.html 前言(闲 ...

随机推荐

  1. hdu3844 Mining Your Own Business,无向双连接组件

    点击打开链接 无向图的双连通分量 #include<cstdio> #include<stack> #include<vector> #include<map ...

  2. yum 安装时错误 Errno 14 Couldn't resolve host 解决办法(转)

    在安装mlocate的时候发现一直报错,错误内容大致如下 Downloading Packages:http://mirrors.163.com/centos/6.5/os/i386/Packages ...

  3. HDU 3831 DICS

    意甲冠军: 按标题给4操作模式  用最少的次数  离a串行转换b弦 思路: 因为操作仅仅有这4种  所以我们能够确定从头到位去匹配a和b一定是正确的 那么状态数一共同拥有多少呢  一共同拥有lengt ...

  4. c++ 学籍管理系统v 1.0

    #include<iostream> #include <string> #include<conio.h> using namespace std; class ...

  5. 让你提前知道软件开发(24):C语言和主要特征的历史

    文章1部分 再次了解C语言 C语言的发展历史和主要特点 作为一门众所周知的计算机编程语言,C语言是谁发明的呢?它是怎样演进的?它有何特点?究竟有多少人在使用它? 1. C语言之父 C语言是1972年由 ...

  6. iOS_动态插入或删除行

    终于效果图: 分MVC三层设计;自己定义的Cell有两种;一种是MainCell,由ModelArr提供数据源;还有一种是插入的cell,由代码创建,而且由另外一个数组供状态数据 数据源部分: wat ...

  7. ExtJS4 表格的嵌套 rowExpander

    今天做一个grid,里面的数据须要带明细,思来想去还是搞个表格嵌套吧!看下图 对于grid中每一条记录点击左边的+号能展开一个明细的子表格 全部数据包含列名均从后台获得,子表格的数据临时在本地以做測试 ...

  8. 第十二章——SQLServer统计信息(1)——创建和更新统计信息

    原文:第十二章--SQLServer统计信息(1)--创建和更新统计信息 简介: 查询的统计信息: 目前为止,已经介绍了选择索引.维护索引.如果有合适的索引并实时更新统计信息,那么优化器会选择有用的索 ...

  9. Hadoop0.20.2 Bloom filter应用演示样例

    1. 简单介绍 參见<Hadoop in Action>P102 以及 <Hadoop实战(第2版)>(陆嘉恒)P69 2. 案例 网上大部分的说明不过依照<Hadoop ...

  10. 基于低压电力采集平台DW710C的基础开发

    实验课题 (1)自己定义通信规约,採用java或C++编写简单的PC端上位机软件,实现採集器与PC机的通信.实验可在DW710C-PCproject下进行. (2)实现LCD显示字符.数字.汉字和简单 ...