ZXingCodeHelper.cs 2.8 KB
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZXing;
using ZXing.Common;

namespace CodeLibrary
{
    public class ZXingCodeHelper
    {
        public static string DecodeQRCode(Bitmap bmp)
        {
            string text = "";
            DecodingOptions option = new DecodingOptions();

            //option.PossibleFormats = new List<BarcodeFormat>() { BarcodeFormat.QR_CODE, BarcodeFormat.All_1D };
            option.PossibleFormats = new List<BarcodeFormat>() { BarcodeFormat.QR_CODE };
            BarcodeReader br = new BarcodeReader();

            br.Options = option;
            Result rs = br.Decode(bmp);

            if (rs == null)
            {
                text = "";
            }
            else
            {
                text = rs.ToString();
                if (!IsGBCode(text))
                {
                    text = ConvertISO88591ToEncoding(text, Encoding.Default);
                }
            }
            return text;
        }
        //转换
        private static string ConvertISO88591ToEncoding(string srcString, Encoding dstEncode)
        {
            String sResult;
            Encoding ISO88591Encoding = Encoding.GetEncoding("ISO-8859-1");
            Encoding GB2312Encoding = Encoding.GetEncoding("GB2312"); //这个地方很特殊,必须利用GB2312编码
            byte[] srcBytes = ISO88591Encoding.GetBytes(srcString);
            //将原本存储ISO-8859-1的字节数组当成GB2312转换成目标编码(关键步骤)
            byte[] dstBytes = Encoding.Convert(GB2312Encoding, dstEncode, srcBytes);
            char[] dstChars = new char[dstEncode.GetCharCount(dstBytes, 0, dstBytes.Length)];
            dstEncode.GetChars(dstBytes, 0, dstBytes.Length, dstChars, 0);//利用char数组存储字符
            sResult = new string(dstChars);
            return sResult;
        }
        /// <summary>
        /// 判断一个word是否为GB2312编码的汉字
        /// </summary>
        /// <param name="word"></param>
        /// <returns></returns>
        private static bool IsGBCode(string word)
        {
            byte[] bytes = Encoding.GetEncoding("GB2312").GetBytes(word);
            if (bytes.Length <= 1) // if there is only one byte, it is ASCII code or other code
            {
                return false;
            }
            else
            {
                byte byte1 = bytes[0];
                byte byte2 = bytes[1];
                if (byte1 >= 176 && byte1 <= 247 && byte2 >= 160 && byte2 <= 254)  //判断是否是GB2312
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

    }
}