Detailed two dimensional code generation factory _c# Tutorial

Source: Internet
Author: User
Tags datetime urlencode

The main share is 3 free two-dimensional code interface of the docking code and testing to draw attention to the points and differences, there is a better way to deal with a lot of communication, mutual promotion of progress; recently in the study of Javsscript extension typescript, the feeling of grammatical sugar is very sweet, mostly with C # more similar, May be the reasons for the Microsoft Project, interested friends can be a lot of mutual exchange;

The above is a personal view, the following to formally share today's article:

    • Google API Two-dimensional code generation interface
    • 2d-code API Two-dimensional code generation interface
    • Topscan API Two-dimensional code generation interface
    • Using object-oriented + load assembly creation objects merge the above interfaces into a two-dimensional code generation factory

The following step to share:

Google API Two-dimensional code generation interface

First of all, here is a Google interface document link Qr_codes document, the enthusiastic friend will open this link right away, the detailed look at the parameters inside this does not make screenshots, roughly commonly used parameters are: API address, content parameters, generate picture width These 3 parameters, Some of the other parameters are the default, different needs can be more detailed look at it; in fact, the first time to see the parameters inside the document, feel less something, such as how can not pass the two-dimensional code in the middle of that icon image address and scan two-dimensional code after how to jump to I want to redirect the URL link it, With this question I have tried many times; here is a description of the results of your attempt:

    • Interface key parameters are: CHT (fixed-value QR), CHL (content parameters), CHS (generated two-dimensional code picture size, format such as: 200x200, here is xyz X is not *)
    • API interface will only generate a two-dimensional code of the picture stream, if you need to save the picture to the local need to go through the browser directly get access to the interface or through the program to download the two-dimensional code
    • If the content parameter passes the text information, the text content will not appear in the middle of the generated two-dimensional code picture, only the two-dimensional code can be scanned by mobile phone to display the transmitted text message on the mobile phone.
    • Content parameters If you pass a simple http://format of the link address, then the mobile phone scan will automatically redirect to the http://link address (this scan redirect can be used to do some products or articles to view)
    • Google interface has not yet developed this logo icon address parameters (I hope to have a friend to study out after sharing with me, thank you)
    • Because the API address is foreign, calling the interface response is not so fast

Second, the above is a personal summary, below we look at the encapsulation of the Request interface method and download two-dimensional code picture method:

#region Generate two dimensional code

 <summary>///generate two-dimensional code///</summary>///<param name= "Content" > Display content (text content or scanned jump http://format address) &l t;/param>///<param name= "Savepath" > Save a two-dimensional Code disk path (default program with directory +qrcode) </param>///<param name= "Logourl" > Logo icon Address (format: http://), (Note: Google interface has not studied this parameter) </param>///<param name= "Apiurl" > Interface address (built-in default API address) </
 param>///<param name= "Wandh" > Width and height (two-dimensional code square, width one to, default) </param>///<returns></returns> Public virtual string Createqrcode (string content = null, string Savepath = null, string logourl = null, string Apiurl = N ull, int? WANDH = null) {var qrname = string.
 Empty; Initialization of the #region parameter Apiurl = Apiurl??
 Apiurl; Content = content??
 Content; Saveqrpath = Savepath??
 Saveqrpath; Logourl = Logourl??
 Logourl; Wandh = Wandh??
 WANDH; #endregion if (string.
 IsNullOrEmpty (Apiurl)) {return qrname;} Apiurl = string.
 Format ("{0}?cht=qr&chl={1}&chs={2}x{2}", Apiurl, Httputility.urlencode (Content), WANDH);Qrname = Downimg (Apiurl, Saveqrpath, imageformat.jpeg);
 return qrname; } #endregion

Download two-dimensional code picture saved to program root:

 #region download pictures///<summary>///download pictures///</summary>///<param name= "url" > Picture download Address </param>///<param name= "Savepath" > Save path Default: IMG folder </param>///<param name= " Format ' > Default:jpeg</param>///<returns> new picture name </returns> public virtual string downimg (string URL, String Savepath = "QRCode", imageformat format = null) {var qrname = string.
 Empty; try {format = format??
 Imageformat.jpeg;
 HttpClient http = new HttpClient (); http.
 Timeout = new TimeSpan (0, 1, 0); using (var stream = http. Getstreamasync (URL). Result) {if (!
 Directory.Exists (Saveqrpath)) {directory.createdirectory (Saveqrpath);}
 Qrname = DateTime.Now.ToString ("yyyymmddhhmmssfff") + "." + format;
 var path = Path.Combine (Savepath, qrname); using (Image img = Image.fromstream (stream)) {img.
 Save (path, format); The catch (Exception ex) {qrname = string.
 Empty;
 return qrname; } #endregion 

The above two methods use a virtual method, because I'm here. The Google interface is used as the default two-dimensional code generator. The next two other interfaces are rewritten with this; the method of downloading pictures is public, and there is no need to rewrite it; here is a fixed parameter to invoke API interface cht= QR, this parameter means to use QR method to generate two-dimensional code, because this API interface also has the function of generating icon, so just want to generate two-dimensional code here is fixed, more generation icon function does not share in this chapter, thank you.

2d-code API Two-dimensional code generation interface

First, the interface needs to register a key via their website, and then from the background to get this key to call the interface address, of course, after the registration has a function is, all of you through the API interface generated two-dimensional code, in addition to their own through the stream, but also through their backstage together to download all the generated pictures, I temporarily did not pay attention to whether the production volume will be charged haha, the following list of interface parameter description and testing points to note:

    • Interface key parameters are: key (registration Get), text (textual parameters), url (after scanning redirect address), logo (logo icon address), size (two-dimensional code square, width)
    • Interface text parameters can only be passed text, not as a scan after the redirection of the address parameters with Google and other interfaces a little different
    • After scanning redirect Address and logo icon address are accessible http://format address link
    • Logo icon Address, the official said that the PNG format is not recommended, the test only JPG success (probably not enough testing here to simply introduce my results)
    • The build speed is faster, and there is also a WordArt generation interface, pretty good
    • API interface will only generate a two-dimensional code of the picture stream, if you need to save the picture to the local need to go through the browser directly get access to the interface or through the program to download the two-dimensional code

Secondly, the encapsulated code is given below, because the download and the code described above are common here do not make statements:

Public Qr_2dcode () {apiurl = "http://www.2d-code.cn/2dcode/api.php"; #region generate two-dimensional code///<summary>///generate two-dimensional code///</summary>///<param name= "Content" > Display content (text content or scanned jump http://format address) </param>///<param name= "Savepath" > Save two-dimensional Code disk path (default program with directory +qrcode) </param>///< param name= "Logourl" > Logo icon Address (format: http://), the official does not recommend the use of PNG format, test only JPG success </param>///<param name= "Directurl" > After scanning redirect address (http://) </param>///<param name= "Apiurl" > Interface address (built-in default API address) </param>///<param name= "Wandh" > Width and height (two-dimensional code square, width one to, default) </param>///<returns></returns> public override string Createqrcode (String content = null, string Savepath = null, string logourl = null, string apiurl = null, int? wandh = null ) {var qrname = string.
 Empty; Initialization of the #region parameter Apiurl = Apiurl??
 Apiurl; Content = content??
 Content; Saveqrpath = Savepath??
 Saveqrpath; Logourl = Logourl??
 Logourl; Wandh = Wandh??
 WANDH; #endregion if (string.IsNullOrEmpty (Apiurl)) {return qrname;} Apiurl = string. Format ("{0}?key=c_d800obbu6hdzjtxpe2yd02imtmpuk9vdcqhe6vrtar4&text={1}&url={2}&logo={3}&size={ 4} ", Apiurl, Httputility.urlencode (content.contains (" http ")?
 "": Content), Httputility.urlencode (content), Httputility.urlencode (Logourl), WANDH);
 Qrname = Downimg (Apiurl, Saveqrpath);
 return qrname;
 } #endregion

Topscan API Two-dimensional code generation interface

First of all, the interface is definitely free, parameter description and Google's similar, the difference is that you can pass the Logo icon address (of course, I have not found that Google can pass the logo parameters, so friends can be ignored); The following description of interface parameters and the points of attention:

    • Interface key parameters are: text (content parameters), logo (logo icon address), W (generated two-dimensional code picture size, format such as: 200x200, here is xyz X is not *)
    • API interface will only generate a two-dimensional code of the picture stream, if you need to save the picture to the local need to go through the browser directly get access to the interface or through the program to download the two-dimensional code
    • If the content parameter passes the text information, the text content will not appear in the middle of the generated two-dimensional code picture, only the two-dimensional code can be scanned by mobile phone to display the transmitted text message on the mobile phone.
    • Content parameters If you pass a simple http://format of the link address, then the mobile phone scan will automatically redirect to the http://link address (this scan redirect can be used to do some products or articles to view)
    • Logo icon Address (format: http://), jpg,png test Pass
    • Test that sometimes the request generated two-dimensional code does not return data, it may be my network problem, the normal generation of two-dimensional code is very fast

Secondly, the encapsulated code is given below, because the download and the code described above are common here do not make statements:

Public Qr_topscan () {apiurl = "http://qr.topscan.com/api.php"; #region generate two-dimensional code///<summary>///generate two-dimensional code///</summary>///<param name= "Content" > Display content (text content or scanned jump http://format address) </param>///<param name= "Savepath" > Save two-dimensional Code disk path (default program with directory +qrcode) </param>///< param name= "Logourl" > Logo icon Address (format: http://), jpg,png test passed, the test was found to be unsuccessful, the reason is not known whether and address related </param>///<param name= " Apiurl "> Interface address (built-in default API address) </param>///<param name=" Wandh "> Width and height (two-dimensional code square, width one to, default) </param>///  <returns></returns> public override string Createqrcode (string content = null, string Savepath = null, string Logourl = null, string apiurl = null, int? WANDH = null) {var qrname = string.
 Empty; Initialization of the #region parameter Apiurl = Apiurl??
 Apiurl; Content = content??
 Content; Saveqrpath = Savepath??
 Saveqrpath; Logourl = Logourl??
 Logourl; Wandh = Wandh??
 WANDH; #endregion if (string.
 IsNullOrEmpty (Apiurl)) {return qrname;} Apiurl = string. FoRmat ("{0}?text={1}&logo={2}&w={3}", Apiurl, Httputility.urlencode (Content), Httputility.urlencode (LOGOURL
 ), WANDH);
 Qrname = Downimg (Apiurl, Saveqrpath);
 return qrname; } #endregion

Using object-oriented + load assembly creation objects merge the above interfaces into a two-dimensional code generation factory

First of all, the analysis of the above 3 interface parameters can be seen, all need fixed parameters: interface API, content (text or jump HTTP address), logo image address (excluding Google temporarily), width and height of these parameters, so we can define a unified parameter class, to pass the parameter information, Here also want to mention because these interfaces are from other people interface to get picture stream, if you want the picture in the execution of the program when directly save in our program local, all need to download, so another parameter: Save the two-dimensional code disk path, so there is a public property:

#region Base configuration information
 ///<summary>
 ///interface Address (required)
 ///</summary>
 protected string apiurl = "https ://chart.googleapis.com/chart ";
 <summary>
 ///Display content (text content), Google text parameter direct transfer HTTP address direct redirect
 ///</summary>
 protected string Content = "http://www.cnblogs.com/wangrudong003/";
 <summary>
 ///The disk path to save the two-dimensional code (default program and directory +qrcode)
 ///</summary>
 protected string saveqrpath = Path.Combine (AppDomain.CurrentDomain.BaseDirectory, "QRCode");
 <summary>
 ///logo image address (http://)
 ///</summary>
 protected string logourl = "yun_qi_img/ 2cf5e0fe9925bc318cb9fe965edf8db1ca1370dc.gif ";
 <summary>
 ///width and height (two-dimensional code square, width one to, default)
 ///</summary>
 protected int wandh =
#endregion

Then, here I don't want each interface to be manually new once to create the object, so you use the module that loads the assembly to create the object you need, so you have the portal to the factory class:

<summary>
 ///Two-dimensional code generation factory
 ///</summary> public
 class qrcodereposity
 {public
 static Baseqrcode current (Qremtype qremtype = qremtype.baseqrcode)
 {
 var nspace = typeof (Baseqrcode);
 var fullName = Nspace. FullName;
 var nowspace = fullname.substring (0, Fullname.lastindexof ('. ') + 1);
 Return assembly.getexecutingassembly (). CreateInstance (Nowspace + qremtype.tostring (), true) as Baseqrcode;
 }
 

Here and the previous cache factory article design is similar, you can check the previous share, but also a lot of praise, thank you; The following code is given below:

<summary>///Factory module definition///</summary> public enum Qremtype {///<summary>///Google interface///&L T;/summary> Baseqrcode,///<summary>///2d-code interface///</summary> qr_2dcode,///<summary>// /Topscan interface///</summary> Qr_topscan}///<summary>///two-dimensional code generation factory///</summary> public class QRC odereposity {public static Baseqrcode current (Qremtype Qremtype = qremtype.baseqrcode) {var nspace = typeof (Baseqrco
 DE); var fullName = Nspace.
 FullName;
 var nowspace = fullname.substring (0, Fullname.lastindexof ('. ') + 1); Return assembly.getexecutingassembly ().
 CreateInstance (Nowspace + qremtype.tostring (), true) as Baseqrcode; }///<summary>///base class uses Google to provide api:https://developers.google.com/chart/infographics/docs/qr_codes, because it is a foreign address, It's relatively slow.///</summary> public class Baseqrcode {#region Base configuration information///<summary>///interface Address (required)///</sum mary> protected String apiurl = "Https://chart.gooGleapis.com/chart "; <summary>///Display content (text content), Google text parameters directly transmit HTTP address direct redirect///</summary> protected string content = "Http://ww
 W.cnblogs.com/wangrudong003/"; <summary>///the disk path where the two-dimensional code is saved (default program and directory +qrcode)///</summary> protected String saveqrpath = Path.Combine (appd Omain.
 Currentdomain.basedirectory, "QRCode"); <summary>///logo image address (http://)///</summary> protected string logourl = "yun_qi_img/2cf5e0fe9925bc318
 Cb9fe965edf8db1ca1370dc.gif ";
 <summary>///width and height (two-dimensional code square, width one to, default)///</summary> protected int wandh = 200; #endregion #region method #region Generate two-dimensional code///<summary>///generate two-dimensional code///</summary>///<param name= "content" & gt; display content (text content or scanned jump http://format address) </param>///<param name= "Savepath" > Save two-dimensional Code disk path (default program with directory +qrcode) </ param>///<param name= "Logourl" > Logo icon Address (format: http://), (Note: Google interface has not studied this parameter) </param>///<param Name = "Apiurl" > Interface address (built-in default API address) </param>/<param name= "Wandh" > Width and height (two-dimensional code square, width one to, default) </param>///<returns></returns> Public Virtual string Createqrcode (string content = null, string Savepath = null, string logourl = null, string apiurl = null, in T? WANDH = null) {var qrname = string.
 Empty; Initialization of the #region parameter Apiurl = Apiurl??
 Apiurl; Content = content??
 Content; Saveqrpath = Savepath??
 Saveqrpath; Logourl = Logourl??
 Logourl; Wandh = Wandh??
 WANDH; #endregion if (string.
 IsNullOrEmpty (Apiurl)) {return qrname;} Apiurl = string.
 Format ("{0}?cht=qr&chl={1}&chs={2}x{2}", Apiurl, Httputility.urlencode (Content), WANDH);
 Qrname = Downimg (Apiurl, Saveqrpath, imageformat.jpeg);
 return qrname; #endregion #region Download pictures///<summary>///download pictures///</summary>///<param name= "url" > Picture download Address </p aram>///<param name= "Savepath" > Save path Default: IMG folder </param>///<param name= "format" > Default: jpeg</ param>///<returns> new picture name </returns> pUblic Virtual string downimg (string url, string savepath = "QRCode", imageformat format = null) {var qrname = string.
 Empty; try {format = format??
 Imageformat.jpeg;
 HttpClient http = new HttpClient (); http.
 Timeout = new TimeSpan (0, 1, 0); using (var stream = http. Getstreamasync (URL). Result) {if (!
 Directory.Exists (Saveqrpath)) {directory.createdirectory (Saveqrpath);}
 Qrname = DateTime.Now.ToString ("yyyymmddhhmmssfff") + "." + format;
 var path = Path.Combine (Savepath, qrname); using (Image img = Image.fromstream (stream)) {img.
 Save (path, format); The catch (Exception ex) {qrname = string.
 Empty;
 return qrname; #endregion #endregion}///<summary>///use 2d-code to provide APIs that need to be registered at the website to obtain key///</summary> public class Qr_
 2dcode:baseqrcode {public Qr_2dcode () {apiurl = "http://www.2d-code.cn/2dcode/api.php"; #region generate two-dimensional code///<summary>///generate two-dimensional code///</summary>///<param name= "Content" > Display content (text content or scanned jump Turn http://latticeAddress) </param>///<param name= "Savepath" > Save two-dimensional code disk path (default program with directory +qrcode) </param>///<param name= " Logourl "> Logo icon Address (format: http://), the official does not recommend the use of PNG format, test only JPG success </param>///<param name=" Directurl "> Post-scan redirect address (http://) </param>///<param name= "Apiurl" > Interface address (built-in default API address) </param>///<param name= " Wandh "> Width and height (two-dimensional code square, width one to, default) </param>///<returns></returns> public override string Createqrcode (String content = null, string Savepath = null, string logourl = null, string apiurl = null, int? wandh = null ) {var qrname = string.
 Empty; Initialization of the #region parameter Apiurl = Apiurl??
 Apiurl; Content = content??
 Content; Saveqrpath = Savepath??
 Saveqrpath; Logourl = Logourl??
 Logourl; Wandh = Wandh??
 WANDH; #endregion if (string.
 IsNullOrEmpty (Apiurl)) {return qrname;} Apiurl = string. Format ("{0}?key=c_d800obbu6hdzjtxpe2yd02imtmpuk9vdcqhe6vrtar4&text={1}&url={2}&logo={3}&size={ 4} ", Apiurl, Httputility.urlencode(Content.contains ("http")?
 "": Content), Httputility.urlencode (content), Httputility.urlencode (Logourl), WANDH);
 Qrname = Downimg (Apiurl, Saveqrpath);
 return qrname;
 #endregion}///<summary>///uses Topscan to provide API///</summary> public class Qr_topscan:baseqrcode {
 Public Qr_topscan () {apiurl = "http://qr.topscan.com/api.php"; #region generate two-dimensional code///<summary>///generate two-dimensional code///</summary>///<param name= "Content" > Display content (text content or scanned jump http://format address) </param>///<param name= "Savepath" > Save two-dimensional Code disk path (default program with directory +qrcode) </param>///< param name= "Logourl" > Logo icon Address (format: http://), jpg,png test passed, the test was found to be unsuccessful, the reason is not known whether and address related </param>///<param name= " Apiurl "> Interface address (built-in default API address) </param>///<param name=" Wandh "> Width and height (two-dimensional code square, width one to, default) </param>///  <returns></returns> public override string Createqrcode (string content = null, string Savepath = null, string Logourl = null, string apiurl = null, int? WAnDH = null) {var qrname = string.
 Empty; Initialization of the #region parameter Apiurl = Apiurl??
 Apiurl; Content = content??
 Content; Saveqrpath = Savepath??
 Saveqrpath; Logourl = Logourl??
 Logourl; Wandh = Wandh??
 WANDH; #endregion if (string.
 IsNullOrEmpty (Apiurl)) {return qrname;} Apiurl = string. Format ("{0}?text={1}&logo={2}&w={3}", Apiurl, Httputility.urlencode (Content), Httputility.urlencode (
 Logourl), WANDH);
 Qrname = Downimg (Apiurl, Saveqrpath);
 return qrname;
 } #endregion}

The content of this article is not so much in program design, the focus is to separate these several interfaces and share the difference between the interface, aspects of friends can copycat and are docking two-dimensional code generation of friends to do the next exchange, nothing more; Key code comments are in the sharing code, there are better or unclear where to welcome the message, thank you.

The above is the entire content of this article, I hope the content of this article for everyone's study or work can bring some help, but also hope that a lot of support cloud Habitat community!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.