本文實(shí)例為大家分享了C#二維碼圖片識別的具體代碼,供大家參考,具體內(nèi)容如下
怎么用NuGet和怎么配置log4net就不介紹了,直接上代碼(Visual Studio 2015 下的項(xiàng)目,用的.NET Framework 4.5.2)。
其中QRDecodeConsoleApp.exe.config文件里配置圖片路勁(默認(rèn)為D:\我的文檔\Pictures\二維碼)、圖片類型(默認(rèn)為*.png)。
也支持在命令行里執(zhí)行,exe后接圖片路勁參數(shù)。
需要直接用的朋友,確認(rèn)完QRDecodeDemo\bin\Debug下的配置文件QRDecodeConsoleApp.exe.config后,運(yùn)行QRDecodeConsoleApp.exe即可(運(yùn)行環(huán)境上文已附鏈接)。
后續(xù)更新一個批量生成二維碼圖片的工具,網(wǎng)上除了在線生成的,下載下來的工具都不怎么好用。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
|
using System; using System.IO; using System.Drawing; using System.Configuration; using ThoughtWorks.QRCode.Codec; using ThoughtWorks.QRCode.Codec.Data; using log4net; namespace QRDecodeConsoleApp { class Program { /// <summary> /// 私有日志對象 /// </summary> private static readonly ILog logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// 識別指定目錄下的全部二維碼圖片(默認(rèn)是PNG) /// </summary> /// <param name="args"></param> static void Main( string [] args) { try { string [] files; if (args.Length > 0) { //args[0]為CMD里exe后的第一個參數(shù) ImgType默認(rèn)配置的*.png files = Directory.GetFiles(args[0], ConfigurationManager.AppSettings[ "ImgType" ]); } else { //讀取指定路勁(QRDecodeConsoleApp.exe.config里配置的路勁) files = Directory.GetFiles(ConfigurationManager.AppSettings[ "QRImgPath" ], ConfigurationManager.AppSettings[ "ImgType" ]); } //存放結(jié)果的文件 string filePath = "txtResult" + DateTime.Now.ToString( "yyyyMMddHHmmssfff" ) + ".config" ; //一個個讀取并追加到記錄文件 for ( int i = 0; i < files.Length; i++) { File.AppendAllText(filePath, CodeDecoder(files[i]) + "\t" + files[i] + "\n" ); //追加到文件里記錄 logger.Info( "第" + i + "個識別成功" ); Console.WriteLine( "第" + i + "個識別成功" ); } Console.WriteLine( "識別完成,按任意鍵退出" ); Console.ReadLine(); } catch (Exception ex) { Console.WriteLine( "識別出錯:" + ex.Message); logger.Error( "識別出錯" ); logger.Error( "異常描述:\t" + ex.Message); logger.Error( "異常方法:\t" + ex.TargetSite); logger.Error( "異常堆棧:\t" + ex.StackTrace); Console.ReadLine(); } } /// <summary> /// 讀取圖片文件,識別二維碼 /// </summary> /// <param name="filePath">圖片文件路勁</param> /// <returns>識別結(jié)果字符串</returns> public static string CodeDecoder( string filePath) { string decoderStr; try { if (!System.IO.File.Exists(filePath)) //判斷有沒有需要讀取的主文件夾,如果不存在,終止 return null ; Bitmap bitMap = new Bitmap(Image.FromFile(filePath)); //實(shí)例化位圖對象,把文件實(shí)例化為帶有顏色信息的位圖對象 QRCodeDecoder decoder = new QRCodeDecoder(); //實(shí)例化QRCodeDecoder //通過.decoder方法把顏色信息轉(zhuǎn)換成字符串信息 decoderStr = decoder.decode( new QRCodeBitmapImage(bitMap), System.Text.Encoding.UTF8); } catch (Exception ex) { throw ex; } return decoderStr; //返回字符串信息 } } } |
代碼鏈接:(QRDecodeDemo.zip)
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://www.cnblogs.com/xuezhizhang/p/8968515.html