C#通過第三方組件生成二維碼(QR Code)和條形碼(Bar Code)
用C#如何生成二維碼,我們可以通過現有的第三方dll直接來實現,下面列出幾種不同的生成方法:
1):通過QrCodeNet(Gma.QrCodeNet.Encoding.dll)來實現
1.1):首先通過VS2015的NuGet下載對應的第三方組件,如下圖所示:
1.2):具體生成二維碼方法如下
private void GenerateQRByQrCodeNet() { QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H); QrCode qrCode = new QrCode(); qrEncoder.TryEncode("Hello World. This is Eric Sun Testing...", out qrCode); GraphicsRenderer renderer = new GraphicsRenderer(new FixedModuleSize(5, QuietZoneModules.Two), Brushes.Black, Brushes.White); using (MemoryStream ms = new MemoryStream()) { renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, ms); Image img = Image.FromStream(ms); img.Save("E:/csharp-qrcode-net.png"); } }
更多詳細信息請參考如下鏈接:
http://www.cnblogs.com/Soar1991/archive/2012/03/30/2426115.html
http://qrcodenet.codeplex.com/
http://stackoverflow.com/questions/7020136/free-c-sharp-qr-code-generator
2):通過ThoughtWorks.QRCode(ThoughtWorks.QRCode.dll)來實現
1.1):首先通過VS2015的NuGet下載對應的第三方組件,如下圖所示:
1.2):具體生成二維碼方法如下
private void GenerateQRByThoughtWorks() { QRCodeEncoder encoder = new QRCodeEncoder(); encoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;//編碼方式(注意:BYTE能支持中文,ALPHA_NUMERIC掃描出來的都是數字) encoder.QRCodeScale = 4;//大小(值越大生成的二維碼圖片像素越高) encoder.QRCodeVersion = 0;//版本(注意:設置為0主要是防止編碼的字符串太長時發生錯誤) encoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;//錯誤效驗、錯誤更正(有4個等級) encoder.QRCodeBackgroundColor = Color.Yellow; encoder.QRCodeForegroundColor = Color.Green; string qrdata = "Hello 世界! This is Eric Sun Testing...."; Bitmap bcodeBitmap = encoder.Encode(qrdata.ToString()); bcodeBitmap.Save(@"E:\HelloWorld.png", ImageFormat.Png); bcodeBitmap.Dispose(); }
3):通過Spire.BarCode(Spire.BarCode.dll)來實現
1.1):首先通過VS2015的NuGet下載對應的第三方組件,如下圖所示:
1.2):具體生成二維碼方法如下
private void GenerateQRBySpire() { BarcodeSettings bs = new BarcodeSettings() { Data = "This is qr code: H2AMK-Z3V69-RTJZD-C7JAU-WILL4", Type = BarCodeType.QRCode, TopTextColor = Color.Red, ShowCheckSumChar = false, ShowText = false }; //Generate the barcode based on the this.barCodeControl1 BarCodeGenerator generator = new BarCodeGenerator(bs); Image barcode = generator.GenerateImage(); //save the barcode as an image barcode.Save(@"E:\barcode-2d.png"); }
1.3):附加具體生成條形碼方法如下
private void GenerateBarCodeBySpire() { BarcodeSettings bs = new BarcodeSettings() { Data = "This is barcode: H2AMK-Z3V69-RTJZD-C7JAU-WILL4", ShowCheckSumChar = false, TopTextColor = Color.Red, ShowTopText = false, ShowTextOnBottom = true }; //Generate the barcode based on the this.barCodeControl1 BarCodeGenerator generator = new BarCodeGenerator(bs); Image barcode = generator.GenerateImage(); //save the barcode as an image barcode.Save(@"E:\barcode.png"); }
1.3):上訴代碼我們發現生成的條形碼和二維碼帶有水印[E-ICEBLUE],如何去除水印呢?請看如下代碼
BarcodeSettings.ApplyKey("......");
請發送郵件到 sales@e-iceblue.com 免費獲取對應的 key 值
更多詳細信息請參考如下鏈接:
http://freebarcode.codeplex.com/
http://www.e-iceblue.com/Knowledgebase/Spire.BarCode/Program-Guide/Programme-Guide-for-Spire.BarCode.html
http://blog.csdn.net/eiceblue/article/details/43405173
4):通過Barcode Rendering Framework(Zen.Barcode.Rendering.Framework.dll)來實現
4.1):首先通過VS2015的NuGet下載對應的第三方組件,如下圖所示:
4.2):具體生成二維碼方法如下
private void GenerateBarCodeByZen() { Code128BarcodeDraw barcode128 = BarcodeDrawFactory.Code128WithChecksum; Image img = barcode128.Draw("Hello World", 40); img.Save("E:/zenbarcode.gif"); }
4.3):附加具體生成條形碼方法如下
private void GenerateQRByZen() { CodeQrBarcodeDraw qrcode = BarcodeDrawFactory.CodeQr; Image img = qrcode.Draw("Hello World!", qrcode.GetDefaultMetrics(40)); img.Save("E:/zenqrcode.gif"); }
更多詳細信息請參考如下鏈接:
http://barcoderender.codeplex.com/
5):通過BarcodeLib(BarcodeLib.Barcode.ASP.NET.dll)來實現,下載對應dll的連接為 http://www.barcodelib.com/asp_net/
5.1):具體生成二維碼方法如下
private void GenerateQRByBarcodeLib() { QRCode qrbarcode = new QRCode(); qrbarcode.Encoding = QRCodeEncoding.Auto; qrbarcode.Data = "336699885522 This is Eric Sun Testing."; qrbarcode.ModuleSize = 10; qrbarcode.LeftMargin = 8; qrbarcode.RightMargin = 8; qrbarcode.TopMargin = 8; qrbarcode.BottomMargin = 8; qrbarcode.ImageFormat = System.Drawing.Imaging.ImageFormat.Gif; // Save QR Code barcode image into your system qrbarcode.drawBarcode("E:/csharp-qrcode-lib.gif"); }
5.2):附加具體生成條形碼方法如下
private void GenerateLinearByBarcodeLib() { Linear barcode = new Linear(); barcode.Type = BarcodeType.CODE128; barcode.Data = "CODE128"; // other barcode settings. // save barcode image into your system barcode.drawBarcode("E:/barcode.png"); }
我們使用的是試用版(帶水印的......),還有付費的正版,詳情請參考如下鏈接:
http://www.barcodelib.com/asp_net/
出處:https://www.cnblogs.com/mingmingruyuedlut/p/6120671.html
=======================================================================================
Net Core 生成二維碼 一維碼
二維碼包QRCoder
生成二維碼幫助類
public interface IQRCodeMoons: ISingletonDependency { Bitmap GetQRCode(string data, int pixel); byte[] GetQrCodeByteArray(string data, int pixel = 4); }
/// <summary> /// 二維碼 /// </summary> public class QRCodeMoons: IQRCodeMoons { /// <summary> /// 生成二維碼 /// </summary> /// <param name="url">存儲內容</param> /// <param name="pixel">像素大小</param> /// <returns></returns> public Bitmap GetQRCode(string data, int pixel) { QRCodeGenerator generator = new QRCodeGenerator(); QRCodeData codeData = generator.CreateQrCode(data, QRCodeGenerator.ECCLevel.M, true); QRCoder.QRCode qrcode = new QRCoder.QRCode(codeData); Bitmap qrImage = qrcode.GetGraphic(pixel, Color.Black, Color.White, true); return qrImage; } /// <summary> /// 生成二維碼並轉成字節 /// </summary> /// <param name="data"></param> /// <param name="pixel"></param> /// <returns></returns> public byte[] GetQrCodeByteArray(string data, int pixel = 4) { var bitmap = GetQRCode(data, pixel); using (MemoryStream ms = new MemoryStream()) { bitmap.Save(ms, ImageFormat.Jpeg); return ms.GetBuffer(); } } }
直接把byte[] 字節返回給前端 前端通過img標簽加載二維碼<img "data:;base64,"+二維碼字節數組 />
前端通過img標簽加載字節中的圖片
1.在angular中 直接這樣通過img加載會報錯 提示不安全的url 需要對這個url進行消毒 進行安全監測
注入消毒對象
private sanitizer: DomSanitizer
對當前地址進行消毒 通過[src] 屬性綁定的方式 不能通過src='{{}}'這種方式綁定值 如果對html本文進行綁定也需要通過bypassSecurityTrustHtml進行消毒
this.imageByte= this.sanitizer.bypassSecurityTrustResourceUrl("data:;base64,"+result.qrCode)
<img *ngIf="data" [src]="imageByte" />
2.可以通過div 設置背景圖片的方式避開這個問題 但是調用js打印的時候無法加載背景圖片
<div [ngStyle]="{'background-image':'url(data:;base64,'+data.qrCode+')'}"></div> <img width="75px" src="data:;base64,{{data.qrCode}}" />
一維碼包BarcodeLib
生成一維碼幫助類
public interface IBarCodeMoons : ISingletonDependency { Image GetBarCode(string data); byte[] GetBarCodeByteArray(string data); }
/// <summary> /// 一維碼 /// </summary> public class BarCodeMoons: IBarCodeMoons { /// <summary> /// 生成一維碼 /// </summary> /// <param name="data">存儲內容</param> /// <returns></returns> public Image GetBarCode(string data) { BarcodeLib.Barcode b = new BarcodeLib.Barcode(); Image img = b.Encode(BarcodeLib.TYPE.CODE128, data, Color.Black, Color.White, 290, 120); return img; } /// <summary> /// 生成一維碼並轉成字節 /// </summary> /// <param name="data"></param> /// <returns></returns> public byte[] GetBarCodeByteArray(string data) { var img = GetBarCode(data); using (MemoryStream ms = new MemoryStream()) { img.Save(ms, ImageFormat.Jpeg); return ms.GetBuffer(); } } }
出處:https://www.cnblogs.com/jiangchengbiao/p/11898577.html
=======================================================================================
C# 利用BarcodeLib.dll生成條形碼(一維,zxing,QrCodeNet/dll二維碼)
首先效果:
1:首先下載BarcodeLib.dll 下載地址 http://pan.baidu.com/share/link?shareid=2590968386&uk=2148890391&fid=1692834292 如果不存在了則自行搜索下載。
1.BarcodeLib.dll 一維條碼庫支持以下條碼格式
UPC-A
UPC-E
UPC 2 Digit Ext.
UPC 5 Digit Ext.
EAN-13
JAN-13
EAN-8
ITF-14
Codabar
PostNet
Bookland/ISBN
Code 11
Code 39
Code 39 Extended
Code 93
LOGMARS
MSI
Interleaved 2 of 5
Standard 2 of 5
Code 128
Code 128-A
Code 128-B
Code 128-C
Telepen
然后項目中添加引用
-
private void button6_Click(object sender, EventArgs e)
-
{
-
System.Drawing.Image image;
-
int width = 148, height = 55;
-
string fileSavePath = AppDomain.CurrentDomain.BaseDirectory + "BarcodePattern.jpg";
-
if (File.Exists(fileSavePath))
-
File.Delete(fileSavePath);
-
GetBarcode(height, width, BarcodeLib.TYPE.CODE128, "20131025-136", out image, fileSavePath);
-
-
pictureBox1.Image = Image.FromFile( "BarcodePattern.jpg");
-
}
-
public static void GetBarcode(int height, int width, BarcodeLib.TYPE type, string code, out System.Drawing.Image image, string fileSaveUrl)
-
{
-
try
-
{
-
image = null;
-
BarcodeLib.Barcode b = new BarcodeLib.Barcode();
-
b.BackColor = System.Drawing.Color.White; //圖片背景顏色
-
b.ForeColor = System.Drawing.Color.Black; //條碼顏色
-
b.IncludeLabel = true;
-
b.Alignment = BarcodeLib.AlignmentPositions.LEFT;
-
b.LabelPosition = BarcodeLib.LabelPositions.BOTTOMCENTER;
-
b.ImageFormat = System.Drawing.Imaging.ImageFormat.Jpeg; //圖片格式
-
System.Drawing.Font font = new System.Drawing.Font( "verdana", 10f); //字體設置
-
b.LabelFont = font;
-
b.Height = height; //圖片高度設置(px單位)
-
b.Width = width; //圖片寬度設置(px單位)
-
-
image = b.Encode(type, code); //生成圖片
-
image.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg);
-
-
}
-
catch (Exception ex)
-
{
-
-
image = null;
-
}
-
}
簡單的寫一下。詳細的去 http://www.barcodelib.com/net_barcode/main.html 這里看。
利用 zxing.dll生成條形碼和二維碼 下載地址http://zxingnet.codeplex.com/
ZXing (ZebraCrossing)是一個開源的,支持多種格式的條形碼圖像處理庫, 。使用該類庫可以方便地實現二維碼圖像的生成和解析。
下載zxing.dll 項目參照引用
-
{
-
MultiFormatWriter mutiWriter = new com.google.zxing.MultiFormatWriter();
-
ByteMatrix bm = mutiWriter.encode(txtMsg.Text, com.google.zxing.BarcodeFormat.QR_CODE, 300, 300);
-
Bitmap img = bm.ToBitmap();
-
pictureBox1.Image = img;
-
-
//自動保存圖片到當前目錄
-
string filename = System.Environment.CurrentDirectory + "\\QR" + DateTime.Now.Ticks.ToString() + ".jpg";
-
img.Save(filename, System.Drawing.Imaging.ImageFormat.Jpeg);
-
lbshow.Text = "圖片已保存到:" + filename;
-
}
-
catch (Exception ee)
-
{ MessageBox.Show(ee.Message); }
利用 QrCodeNet.dll生成條形碼和二維碼 下載地址http://qrcodenet.codeplex.com/
下載QrCodeNet.dll 項目參照引用
-
private void button2_Click(object sender, EventArgs e)
-
{
-
var codeParams = CodeDescriptor.Init(ErrorCorrectionLevel.H, textBox1.Text.Trim(), QuietZoneModules.Two, 5);
-
-
codeParams.TryEncode();
-
-
// Render the QR code as an image
-
using ( var ms = new MemoryStream())
-
{
-
codeParams.Render(ms);
-
-
Image image = Image.FromStream(ms);
-
pictureBox1.Image = image;
-
if (image != null)
-
pictureBox1.SizeMode = image.Height > pictureBox1.Height ? PictureBoxSizeMode.Zoom : PictureBoxSizeMode.Normal;
-
}
-
-
}
-
/// <summary>
-
/// Class containing the description of the QR code and wrapping encoding and rendering.
-
/// </summary>
-
internal class CodeDescriptor
-
{
-
public ErrorCorrectionLevel Ecl;
-
public string Content;
-
public QuietZoneModules QuietZones;
-
public int ModuleSize;
-
public BitMatrix Matrix;
-
public string ContentType;
-
-
/// <summary>
-
/// Parse QueryString that define the QR code properties
-
/// </summary>
-
/// <param name="request">HttpRequest containing HTTP GET data</param>
-
/// <returns>A QR code descriptor object</returns>
-
public static CodeDescriptor Init(ErrorCorrectionLevel level, string content, QuietZoneModules qzModules, int moduleSize)
-
{
-
var cp = new CodeDescriptor();
-
-
Error correction level
-
cp.Ecl = level;
-
Code content to encode
-
cp.Content = content;
-
Size of the quiet zone
-
cp.QuietZones = qzModules;
-
Module size
-
cp.ModuleSize = moduleSize;
-
return cp;
-
}
-
-
/// <summary>
-
/// Encode the content with desired parameters and save the generated Matrix
-
/// </summary>
-
/// <returns>True if the encoding succeeded, false if the content is empty or too large to fit in a QR code</returns>
-
public bool TryEncode()
-
{
-
var encoder = new QrEncoder(Ecl);
-
QrCode qr;
-
if (!encoder.TryEncode(Content, out qr))
-
return false;
-
-
Matrix = qr.Matrix;
-
return true;
-
}
-
-
/// <summary>
-
/// Render the Matrix as a PNG image
-
/// </summary>
-
/// <param name="ms">MemoryStream to store the image bytes into</param>
-
internal void Render(MemoryStream ms)
-
{
-
var render = new GraphicsRenderer( new FixedModuleSize(ModuleSize, QuietZones));
-
render.WriteToStream(Matrix, System.Drawing.Imaging.ImageFormat.Png, ms);
-
ContentType = "image/png";
-
}
-
}
效果:
參考地址:
http://www.cnblogs.com/mzlee/archive/2011/03/19/Lee_Barcode.html
http://blog.163.com/smxp_2006/blog/static/588682542010215163803/
http://q.cnblogs.com/q/15253/
http://www.csharpwin.com/csharpspace/13364r9803.shtml
http://www.2cto.com/kf/201304/203035.html
出處:https://blog.csdn.net/kongwei521/article/details/17588825
=======================================================================================
C#打印標簽(包括二維碼和一位條碼)
主要用到第三方庫ZXing.net來生成各種條碼。用PrintDocument來打印。很簡單也很實用。
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 System.IO;
using ZXing;
using ZXing.Common;
using ZXing.QrCode;
namespace Printtest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
EncodingOptions encodeOption = new EncodingOptions();
encodeOption.Height = 50; // 高度、寬度
encodeOption.Width = 120;
ZXing.BarcodeWriter wr = new BarcodeWriter();
wr.Options = encodeOption;
wr.Format = BarcodeFormat.CODE_39; // 條形碼規格
Bitmap img = wr.Write("D1234B678A"); // 生成圖片
string filePath = System.AppDomain.CurrentDomain.BaseDirectory + "\\EAN_13-" + "test" + ".jpg";
img.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
private void button2_Click(object sender, EventArgs e)
{
ZXing.QrCode.QrCodeEncodingOptions qrEncodeOption = new ZXing.QrCode.QrCodeEncodingOptions();
qrEncodeOption.CharacterSet = "UTF-8"; // 設置編碼格式,否則讀取'中文'亂碼
qrEncodeOption.Height = 30;
qrEncodeOption.Width = 30;
qrEncodeOption.Margin = 1; // 設置周圍空白邊距
// 2.生成條形碼圖片並保存
ZXing.BarcodeWriter wr = new BarcodeWriter();
wr.Format = BarcodeFormat.DATA_MATRIX; // 二維碼
wr.Options = qrEncodeOption;
Bitmap img = wr.Write("D1234B678A");
string filePath = System.AppDomain.CurrentDomain.BaseDirectory + "\\QR-" + "test2" + ".jpg";
img.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
pictureBox1.Load(filePath);
}
private void button3_Click(object sender, EventArgs e)
{
this.printDocument1.DefaultPageSettings.PaperSize = new System.Drawing.Printing.PaperSize("Custom",220, 120);
//PrintPreviewDialog printPreviewDialog = new PrintPreviewDialog();
//printPreviewDialog.Document = printDocument1; 打印預覽代碼
try
{
printDocument1.Print();
}
catch(Exception excep)
{
MessageBox.Show(excep.Message, "打印出錯", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
Bitmap img = new Bitmap(Image.FromFile(System.AppDomain.CurrentDomain.BaseDirectory + "\\EAN_13-" + "test" + ".jpg"));
e.Graphics.DrawString("A1234B678A", new Font(new FontFamily("黑體"), 11), System.Drawing.Brushes.Black, 5, 5);
e.Graphics.DrawImage(img, 10, 30);
//e.Graphics.DrawString("D1234B678A", new Font(new FontFamily("黑體"), 11), System.Drawing.Brushes.Black, 10, 90);
e.Graphics.DrawImage(pictureBox1.Image, 150, 80);
}
}
}
最終效果:
出處:https://blog.csdn.net/mycoolme5/article/details/85323407
=======================================================================================
C#利用ZXing.Net生成條形碼和二維碼
本文是利用ZXing.Net在WinForm中生成條形碼,二維碼的小例子,僅供學習分享使用,如有不足之處,還請指正。
什么是ZXing.Net?
ZXing是一個開放源碼的,用Java實現的多種格式的1D/2D條碼圖像處理庫,它包含了聯系到其他語言的端口。而ZXing.Net是ZXing的端口之一。
在工程中引用ZXing.Net
在項目中,點擊項目名稱右鍵-->管理NuGet程序包,打開NuGet包管理器窗口,進行搜索下載即可,如下圖所示:
ZXing.Net關鍵類結構圖
包括Reader【識別圖片中的條形碼和二維碼】) 和Writer【生成條形碼和二維碼到圖片中】兩部分,如下圖所示:
涉及知識點:
BarcodeWriter 用於生成圖片格式的條碼類,通過Write函數進行輸出。繼承關系如上圖所示。
BarcodeFormat 枚舉類型,條碼格式
QrCodeEncodingOptions 二維碼設置選項,繼承於EncodingOptions,主要設置寬,高,編碼方式等信息。
MultiFormatWriter 復合格式條碼寫碼器,通過encode方法得到BitMatrix。
BitMatrix 表示按位表示的二維矩陣數組,元素的值用true和false表示二進制中的1和0。
示例效果圖
關鍵代碼
如下所示,包含一維條碼,二維條碼,和帶logo的條碼
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
|
using
System;
using
System.Collections.Generic;
using
System.Drawing;
using
System.Drawing.Imaging;
using
System.Linq;
using
System.Text;
using
System.Threading.Tasks;
using
ZXing;
using
ZXing.Common;
using
ZXing.QrCode;
using
ZXing.QrCode.Internal;
namespace
DemoQrCode
{
/// <summary>
/// 描述:條形碼和二維碼幫助類
/// 時間:2018-02-18
/// </summary>
public
class
BarcodeHelper
{
/// <summary>
/// 生成二維碼
/// </summary>
/// <param name="text">內容</param>
/// <param name="width">寬度</param>
/// <param name="height">高度</param>
/// <returns></returns>
public
static
Bitmap Generate1(
string
text,
int
width,
int
height)
{
BarcodeWriter writer =
new
BarcodeWriter();
writer.Format = BarcodeFormat.QR_CODE;
QrCodeEncodingOptions options =
new
QrCodeEncodingOptions()
{
DisableECI =
true
,
//設置內容編碼
CharacterSet =
"UTF-8"
,
//設置二維碼的寬度和高度
Width = width,
Height = height,
Margin = 1
//設置二維碼的邊距,單位不是固定像素
};
writer.Options = options;
Bitmap map = writer.Write(text);
return
map;
}
/// <summary>
/// 生成一維條形碼
/// </summary>
/// <param name="text">內容</param>
/// <param name="width">寬度</param>
/// <param name="height">高度</param>
/// <returns></returns>
public
static
Bitmap Generate2(
string
text,
int
width,
int
height)
{
BarcodeWriter writer =
new
BarcodeWriter();
//使用ITF 格式,不能被現在常用的支付寶、微信掃出來
//如果想生成可識別的可以使用 CODE_128 格式
//writer.Format = BarcodeFormat.ITF;
writer.Format = BarcodeFormat.CODE_39;
EncodingOptions options =
new
EncodingOptions()
{
Width = width,
Height = height,
Margin = 2
};
writer.Options = options;
Bitmap map = writer.Write(text);
return
map;
}
/// <summary>
/// 生成帶Logo的二維碼
/// </summary>
/// <param name="text">內容</param>
/// <param name="width">寬度</param>
/// <param name="height">高度</param>
public
static
Bitmap Generate3(
string
text,
int
width,
int
height)
{
//Logo 圖片
string
logoPath = System.AppDomain.CurrentDomain.BaseDirectory +
@"\img\logo.png"
;
Bitmap logo =
new
Bitmap(logoPath);
//構造二維碼寫碼器
MultiFormatWriter writer =
new
MultiFormatWriter();
Dictionary<EncodeHintType,
object
> hint =
new
Dictionary<EncodeHintType,
object
>();
hint.Add(EncodeHintType.CHARACTER_SET,
"UTF-8"
);
hint.Add(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
//hint.Add(EncodeHintType.MARGIN, 2);//舊版本不起作用,需要手動去除白邊
//生成二維碼
BitMatrix bm = writer.encode(text, BarcodeFormat.QR_CODE, width+30, height+30, hint);
bm = deleteWhite(bm);
BarcodeWriter barcodeWriter =
new
BarcodeWriter();
Bitmap map = barcodeWriter.Write(bm);
//獲取二維碼實際尺寸(去掉二維碼兩邊空白后的實際尺寸)
int
[] rectangle = bm.getEnclosingRectangle();
//計算插入圖片的大小和位置
int
middleW = Math.Min((
int
)(rectangle[2] / 3), logo.Width);
int
middleH = Math.Min((
int
)(rectangle[3] / 3), logo.Height);
int
middleL = (map.Width - middleW) / 2;
int
middleT = (map.Height - middleH) / 2;
Bitmap bmpimg =
new
Bitmap(map.Width, map.Height, PixelFormat.Format32bppArgb);
using
(Graphics g = Graphics.FromImage(bmpimg))
{
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.DrawImage(map, 0, 0,width,height);
//白底將二維碼插入圖片
g.FillRectangle(Brushes.White, middleL, middleT, middleW, middleH);
g.DrawImage(logo, middleL, middleT, middleW, middleH);
}
return
bmpimg;
}
/// <summary>
/// 刪除默認對應的空白
/// </summary>
/// <param name="matrix"></param>
/// <returns></returns>
private
static
BitMatrix deleteWhite(BitMatrix matrix)
{
int
[] rec = matrix.getEnclosingRectangle();
int
resWidth = rec[2] + 1;
int
resHeight = rec[3] + 1;
BitMatrix resMatrix =
new
BitMatrix(resWidth, resHeight);
resMatrix.clear();
for
(
int
i = 0; i < resWidth; i++)
{
for
(
int
j = 0; j < resHeight; j++)
{
if
(matrix[i + rec[0], j + rec[1]])
resMatrix[i, j]=
true
;
}
}
return
resMatrix;
}
}
}
|
關於生成條形碼和二維碼的方式有很多,條碼的種類也有很多種,每一種都有其對應的應用領域。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
出處:https://www.jb51.net/article/136698.htm
=======================================================================================
根據上面的最后一篇文章的介紹,我自己修改了下,適用於自己的項目中:
namespace ConsoleQrCode { using System.Drawing; using System.Drawing.Imaging; using ZXing; using ZXing.Common; using ZXing.QrCode; using ZXing.QrCode.Internal; /// <summary> /// 描述:條形碼和二維碼幫助類 /// 時間:2018-02-18 /// </summary> public class BarcodeHelper { /// <summary> /// 生成一維條形碼的數據矩陣 /// </summary> /// <param name="text"></param> /// <param name="width"></param> /// <param name="height"></param> /// <returns></returns> public static BitMatrix GenerateBitMatrix(string text, int width, int height) { BarcodeWriter writer = new BarcodeWriter(); //使用ITF 格式,不能被現在常用的支付寶、微信掃出來 //如果想生成可識別的可以使用 CODE_128 格式 //writer.Format = BarcodeFormat.ITF; writer.Format = BarcodeFormat.CODE_128; writer.Format = BarcodeFormat.QR_CODE; EncodingOptions options = new EncodingOptions() { Width = 20, Height = 10, GS1Format = false, PureBarcode = false, Margin = 0 }; writer.Options = options; BitMatrix bm = writer.Encode(text); //bm = deleteWhite(bm); return bm; } /// <summary> /// 生成一維條形碼 /// </summary> /// <param name="text">內容</param> /// <param name="width">寬度</param> /// <param name="height">高度</param> /// <returns></returns> public static Bitmap GenerateBarCode(string text, int width, int height) { BarcodeWriter writer = new BarcodeWriter(); //使用ITF 格式,不能被現在常用的支付寶、微信掃出來 //如果想生成可識別的可以使用 CODE_128 格式 //writer.Format = BarcodeFormat.ITF; writer.Format = BarcodeFormat.CODE_128; EncodingOptions options = new EncodingOptions() { Width = width, Height = height, //GS1Format = false, //PureBarcode = true, Margin = 2 }; writer.Options = options; BitMatrix bm = writer.Encode(text); //Bitmap b = writer.Write(bm); Bitmap b = writer.Write(text); return b; } /// <summary> /// 生成二維碼 /// </summary> /// <param name="text">內容</param> /// <param name="width">寬度</param> /// <param name="height">高度</param> /// <returns></returns> public static Bitmap GenerateQrCode(string text, int width, int height) { BarcodeWriter writer = new BarcodeWriter(); writer.Format = BarcodeFormat.QR_CODE; QrCodeEncodingOptions options = new QrCodeEncodingOptions() { DisableECI = true,//設置內容編碼 CharacterSet = "UTF-8", //設置二維碼的寬度和高度 Width = width, Height = height, Margin = 1//設置二維碼的邊距,單位不是固定像素 }; writer.Options = options; Bitmap map = writer.Write(text); return map; } /// <summary> /// 生成帶Logo的二維碼 /// </summary> /// <param name="text">內容</param> /// <param name="width">寬度</param> /// <param name="height">高度</param> public static Bitmap GenerateQrCodeForLogo(string text, int width, int height) { //Logo 圖片 string logoPath = System.AppDomain.CurrentDomain.BaseDirectory + @"\logo.jpg"; Bitmap logo = new Bitmap(logoPath); //構造二維碼寫碼器 MultiFormatWriter writer = new MultiFormatWriter(); Dictionary<EncodeHintType, object> hint = new Dictionary<EncodeHintType, object>(); hint.Add(EncodeHintType.CHARACTER_SET, "UTF-8"); hint.Add(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); //hint.Add(EncodeHintType.MARGIN, 2);//舊版本不起作用,需要手動去除白邊 //生成二維碼 BitMatrix bm = writer.encode(text, BarcodeFormat.QR_CODE, width + 30, height + 30, hint); bm = deleteWhite(bm); BarcodeWriter barcodeWriter = new BarcodeWriter(); Bitmap map = barcodeWriter.Write(bm); //獲取二維碼實際尺寸(去掉二維碼兩邊空白后的實際尺寸) int[] rectangle = bm.getEnclosingRectangle(); //計算插入圖片的大小和位置 int middleW = Math.Min((int)(rectangle[2] / 3), logo.Width); int middleH = Math.Min((int)(rectangle[3] / 3), logo.Height); int middleL = (map.Width - middleW) / 2; int middleT = (map.Height - middleH) / 2; Bitmap bmpimg = new Bitmap(map.Width, map.Height, PixelFormat.Format32bppArgb); using (Graphics g = Graphics.FromImage(bmpimg)) { g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; g.DrawImage(map, 0, 0, width, height); //白底將二維碼插入圖片 g.FillRectangle(Brushes.White, middleL, middleT, middleW, middleH); g.DrawImage(logo, middleL, middleT, middleW, middleH); } return bmpimg; } /// <summary> /// 刪除默認對應的空白 /// </summary> /// <param name="matrix"></param> /// <returns></returns> private static BitMatrix deleteWhite(BitMatrix matrix) { int[] rec = matrix.getEnclosingRectangle(); int resWidth = rec[2] + 1; int resHeight = rec[3] + 1; BitMatrix resMatrix = new BitMatrix(resWidth, resHeight); resMatrix.clear(); for (int i = 0; i < resWidth; i++) { for (int j = 0; j < resHeight; j++) { if (matrix[i + rec[0], j + rec[1]]) resMatrix[i, j] = true; } } return resMatrix; } } }
調用方式:
static void Main(string[] args) { Console.WriteLine(@"Type some text to QR code: "); string sampleText = Console.ReadLine(); sampleText = "MU8888 0731ANGB080"; DateTime dt = DateTime.Now; BarcodeHelper.GenerateBarCode(sampleText, 90, 50).Save("ZXing.Net" + dt.ToString("HHmmss-fff") + "_BarCode.jpg", System.Drawing.Imaging.ImageFormat.Jpeg); BarcodeHelper.GenerateQrCode(sampleText, 200, 200).Save("ZXing.Net" + dt.ToString("HHmmss-fff") + "_QrCode.jpg", System.Drawing.Imaging.ImageFormat.Jpeg); //BarcodeHelper.GenerateQrCodeForLogo(sampleText, 200, 200).Save("ZXing.Net" + DateTime.Now.ToString("HHmmss-fff") + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg); ZXing.Common.BitMatrix bm = BarcodeHelper.GenerateBitMatrix(sampleText, 1, 1); Console.WriteLine(); Console.WriteLine(); Console.BackgroundColor = ConsoleColor.White; for (int i = 0; i < qrCode.Matrix.Width + 2; i++) Console.Write(" ");//中文全角的空格符 Console.WriteLine(); for (int j = 0; j < bm.Height; j++) { for (int i = 0; i < bm.Width; i++) { //char charToPoint = qrCode.Matrix[i, j] ? '█' : ' '; Console.Write(i == 0 ? " " : "");//中文全角的空格符 Console.BackgroundColor = bm[i, j] ? ConsoleColor.Black : ConsoleColor.White; Console.Write(' ');//中文全角的空格符 Console.BackgroundColor = ConsoleColor.White; Console.Write(i == bm.Width - 1 ? " " : "");//中文全角的空格符 //Console.Write(""); } Console.WriteLine(); } for (int i = 0; i < qrCode.Matrix.Width + 2; i++) Console.Write(" ");//中文全角的空格符 Console.BackgroundColor = ConsoleColor.Black; Console.WriteLine(); Console.WriteLine(); Console.WriteLine(@"Press any key to quit."); Console.ReadKey(); }
=======================================================================================
.Net Core上也可以使用的二維碼組件
我Fork了QRCoder,並且兼容了.Net Core,圖形庫用的是ZKWeb.System.Drawing
Github: https://github.com/zkweb-framework/QRCoder
Nuget: https://www.nuget.org/packages/ZKWeb.Fork.QRCoder
使用方法請參考原github上的文檔:https://github.com/codebude/QRCoder
出處:https://www.cnblogs.com/zkweb/p/6163506.html
=======================================================================================