Unity3D生成和识别二维码

用到的插件:ZXing.Net 去网上下载,并导入Unity中 。具体请先看

参考文章:http://blog.csdn.net/u010019717/article/details/51867869

请直接看代码:

using System.Threading;
using UnityEngine.UI;
using UnityEngine;
using System.Collections;
using ZXing;
using ZXing.QrCode;
using ZXing.Common;
using System.IO;
using UnityEngine.Events;
using System;
using ZXing.Rendering;
using ZXing.Maxicode;
using System.Collections.Generic;
using DG.Tweening;

namespace XD.TTM
{
    /// <summary>
    /// 创建 ,扫描 二维码
    /// </summary>
    public class BarcodeCam : MonoBehaviour
    {

        public static Color infoColor = Color.black;

        private static Texture2D encoded;
        private string Rstext;          // ZXing解析的 结果  
                                        //private string TESTstr;    // 网络返回的验证数据结果  
        private int sw, sh;
        public static string driverID;   // 设备唯一标识   
        public RawImage camsx;       // UI上用于显示摄像头显示的内容  
        public Quaternion baseRotation;

        // 代表着摄像机  
        private WebCamTexture camTexture = null;
        private Thread qrThread;

        private Color32[] c;
        private int cw, ch;
        //private Rect screenRect;
        private bool isQuit;


        private string QRscan;
        private bool shouldEncodeNow;
        private static UnityAction<string> scannerCallBack = null;


        void OnGUI()
        {

            //GUI.Label(screenRect, driverID);
            //GUI.DrawTexture(new Rect(200, 100, 256, 256), encoded);
        }

        void OnEnable()
        {
            // 开启相机  
            if (camTexture != null)
            {
                Debug.Log("OnEnable");
                camTexture.Play();
                cw = camTexture.width;
                ch = camTexture.height;
            }
        }

        void OnDisable()
        {
            // 暂停 相机  
            if (camTexture != null)
            {
                Debug.Log("OnDisable");
                camTexture.Pause();
            }
        }

        void OnDestroy()
        {
            if (camTexture != null)
            {
                if (qrThread.IsAlive && camTexture.isPlaying)
                {
                    Debug.Log("OnDestroy");
                    qrThread.Abort();
                    camTexture.Stop();
                }
            }
        }
        void OnApplicationQuit()
        {
            isQuit = true;
        }
        void Awake()
        {

            camsx = this.transform.Find("Parent/ScannerCam").GetComponent<RawImage>();
        }

        void Start()
        {
            (this.transform as RectTransform).sizeDelta = new Vector2(Screen.width, Screen.height);
            this.transform.localScale = GameUIControl.Instance.ScaleToWidthAndHeight();
            camsx.rectTransform.localPosition = Vector2.zero;
            camsx.transform.localRotation = Quaternion.Euler(0, 0, -90);
            baseRotation = camsx.transform.rotation;
            shouldEncodeNow = false;

            encoded = new Texture2D(256, 256);
            WebCamDevice[] devices = WebCamTexture.devices;
            if (devices.Length <= 0)
            {
                Debug.Log("No camera available !");
                return;
            }

            StartCoroutine(startCam());
        }

        IEnumerator startCam()
        {

            camsx.color = new Color(1, 1, 1, 1);
            yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);//申请打开摄像头
            if (Application.HasUserAuthorization(UserAuthorization.WebCam))
            {
                Debug.Log("Open Camrea!");

                camTexture = new WebCamTexture();
                if (Screen.width < 1280)
                {
                    sw = 640;
                }
                else
                {
                    sw = 1280;
                }

                // 在 Unity界面上显示  扫描的内容  
                camTexture.requestedHeight = 720;
                camTexture.requestedWidth = sw;
                //camTexture.wrapMode = TextureWrapMode.Repeat;
                camsx.texture = camTexture;
                camsx.material.mainTexture = camTexture;
                OnEnable();

                qrThread = new Thread(DecodeQR);
                qrThread.Start();

            }
        }

        public void show(UnityAction<string> callBack)
        {
            scannerCallBack = callBack;
            Screen.orientation = ScreenOrientation.LandscapeLeft;
            base.show(); 
        }

        void Update()
        {
            // 获取扫描的内容  
            if (camTexture == null)
                return;
            //camsx.transform.rotation = baseRotation* Quaternion.AngleAxis(camTexture.videoRotationAngle, Vector3.up);
            if ((c == null) && (camTexture.isPlaying))
            {
                c = camTexture.GetPixels32();
                cw = camTexture.width;
                ch = camTexture.height;
            }

            Rstext = driverID;

            camsx.enabled = false;

            camsx.enabled = true;

            var textForEncoding = driverID;
            if (shouldEncodeNow &&
                textForEncoding != null)
            {
                var color32 = Encode(textForEncoding, encoded.width, encoded.height);
                encoded.SetPixels32(color32);
                encoded.Apply();
                shouldEncodeNow = false;
                if (QRscan != driverID)
                {
                    QRscan = driverID;
                    // todo 如果遇到新的 二维码那么就执行 其他的操作(网络请求验证啊等等)  
                    //StartCoroutine(CheckCode(LastResult));  
                    scannerResult();
                }
            }
        }
        /// <summary>
        ///执行扫描结果
        /// </summary>
        void scannerResult()
        { 
            if (scannerCallBack != null)
            {
                scannerCallBack(QRscan);
                scannerCallBack = null;
            } 
        } 


        /// <summary>
        /// 解码 扫描的内容  
        /// </summary>
        void DecodeQR()
        {
            var barcodeReader = new BarcodeReader { AutoRotate = false, TryHarder = false };

            while (true)
            {
                if (isQuit)
                    break;

                try
                {

                    if (c != null)
                    {
                        var result = barcodeReader.Decode(c, cw, ch);
                        if (result != null)
                        {
                            driverID = result.Text;
                            shouldEncodeNow = true;
                        }

                        Thread.Sleep(200);
                        c = null;
                    }
                }
                catch
                {
                }
            }
        }
        /// <summary>
        /// 解码本地图片
        /// </summary>
        /// <returns>The local picture.</returns>
        /// <param name="text2d">Text2d.</param>
        public static string DecodeLocalPicture(Texture2D text2d)
        {

            Color32[] _c = text2d.GetPixels32();
            int _cw = text2d.width;
            int _ch = text2d.height;
            string _result = string.Empty;
            var barcodeReader = new BarcodeReader { AutoRotate = false, TryHarder = false };


            try
            { 
                if (_c != null)
                {
                    var result = barcodeReader.Decode(_c, _cw, _ch);
                    if (result != null)
                    {
                        _result = result.Text;
                    } 
                }
            }
            catch (System.Exception e)
            {
                Debug.Log(e);
            }

            return _result;
        }


        #region   生成 二维码
        /// <summary>
        /// 创建二维码
        /// </summary>
        /// <returns>The qr code image.</returns>
        /// <param name="QrCodeImg">Qr code image.</param>
        public static IEnumerator createQrCodeImage(Image QrCodeImg, string newDriverID)
        {
            //设备唯一ID     
            Texture2D texture2d = EncodeUTF_8(newDriverID, 256, 265);
            byte[] textureBytes = texture2d.EncodeToPNG();

            yield return new WaitForEndOfFrame();

            string filePath = Application.persistentDataPath + "/QRCodeFile/";
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }

            File.WriteAllBytes(filePath + "myQrCode.png", textureBytes);
            if (Application.platform == RuntimePlatform.IPhonePlayer)
                IOSAlbumCamera.iosSaveImageToPhotosAlbum(filePath + "myQrCode.png");//将二维码也存在相册里
            Sprite sp = GameUtil.createSprite(texture2d);
            sp.texture.filterMode = FilterMode.Point;
            sp.texture.Apply();
            QrCodeImg.sprite = sp;

        }
        /// <summary>
        /// 生成二维码
        /// </summary>
        /// <returns>The encode.</returns>
        /// <param name="textForEncoding">Text for encoding.</param>
        /// <param name="width">Width.</param>
        /// <param name="height">Height.</param>
        private static Color32[] Encode(string textForEncoding, int width, int height)
        {

            var writer = new BarcodeWriter
            {
                Format = BarcodeFormat.QR_CODE,
                Options = new QrCodeEncodingOptions
                {
                    Height = height,
                    Width = width
                }
            };
            return writer.Write(textForEncoding);
        }

        /// <summary>
        /// 生成二维码 the UTF8.
        /// </summary>
        /// <returns>The UTF8.</returns>
        /// <param name="context">Context.</param>
        /// <param name="width">Width.</param>
        /// <param name="height">Height.</param>
        private static Texture2D EncodeUTF_8(string context, int width, int height)
        {
            //设置二维码大小  
            encoded = new Texture2D(width, height);
            //二维码边框  
            BitMatrix BIT;
            Dictionary<EncodeHintType, object> hints = new Dictionary<EncodeHintType, object>();
            //设置编码方式  
            hints.Add(EncodeHintType.MARGIN, 1);
            hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
            BIT = new MultiFormatWriter().encode(context, BarcodeFormat.QR_CODE, width, height, hints);

            for (int x = 0; x < height; x++)
            {
                for (int y = 0; y < width; y++)
                {
                    if (BIT[x, y])
                    {
                        encoded.SetPixel(y, x, infoColor);
                    }
                    else
                    {
                        encoded.SetPixel(y, x, Color.white);
                    }

                }
            }
            encoded.Apply();
            return encoded;
        }
        #endregion
    }

}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值