[C#][QR Code 一維碼、二維碼]

  • 5844
  • 0

使用ZXing套件,在WinForm讀取與產生一維、二維碼。

步驟流程

  1. Nuget下載ZXing套件
  2. 產生二維碼
  3. 產生一維碼
  4. 讀取一、二維碼

1. Nuget下載ZXing套件

"管理Nuget套件"搜尋ZXing,下載ZXingNet

2. 產生二維碼

private Bitmap CreateQRCode(string content)
{
    ZXing.BarcodeWriter writer = new ZXing.BarcodeWriter
    {
        //要產生的Code類型
        Format = ZXing.BarcodeFormat.QR_CODE,
        //產生圖形的屬性
        Options = new ZXing.QrCode.QrCodeEncodingOptions
        {
            Height = 250,   //圖形的高
            Width = 250,    //圖形的寬
            CharacterSet = "UTF-8",  //編碼格式 UTF-8  中文才不會出現亂
            //錯誤修正內容
            ErrorCorrection = ZXing.QrCode.Internal.ErrorCorrectionLevel.M
        
    };
    var bm = writer.Write(content);
    return bm;
}

3. 產生一維碼

private Bitmap CreateBarCode(string content)
{
    BarcodeWriter barcodeWriter = new BarcodeWriter
    {
        Format = BarcodeFormat.CODE_128,
        Options = new EncodingOptions
        {
            Height = 100,
            Width = 200,
            PureBarcode = false,
            Margin = 0
        }
    };
    var barCode = barcodeWriter.Write(content);
    return barCode;
}

4.讀取一、二維碼

private string ReadCode(string filePath)
{
    //filePath 可以是一維或二維碼
    ZXing.IBarcodeReader reader = new ZXing.BarcodeReader();
    FileStream fs = new FileStream(filePath, FileMode.Open);

    Byte[] data = new Byte[fs.Length];
    fs.Read(data, 0, data.Length);
    fs.Close();

    MemoryStream ms = new MemoryStream(data);
    var bitmap = (Bitmap)Image.FromStream(ms);

    ZXing.Result result = reader.Decode(bitmap);
    return result.ToString();
}