美文网首页插件推荐
ZXing生成保存,识别二维码

ZXing生成保存,识别二维码

作者: 萧非子 | 来源:发表于2017-11-13 18:52 被阅读14次

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.UI;
    using ZXing;//引入ZXing,下载zxing.unity.dll

    public class QRCode : MonoBehaviour {
    public RawImage cameraTexture;
    public RawImage QRCodeTexture;

    private WebCamTexture webCamTexture;
    private BarcodeReader barcodeReader;//识别二维码
    private BarcodeWriter barcodeWriter;//生成二维码
    private  float interval = 0f;
    private bool isStartS = false;//开始扫描二维码
    
    private bool m_IsEditorSaveTexture = false; //这里保证上次svn的时候是false,否则每次都要生成新资源
    private  string QRTextureSavedPath;
    private Color32[] data;//
    void Start () {
    
        barcodeReader = new BarcodeReader();
        QRTextureSavedPath = Application.dataPath + "/QRCodeTexture"; //二维码保存路径,程序内
        // QRTextureSavedPath = Application.persistentDataPath + "/QRCodeTexture";//二维码保存路径,沙盒
    
    }
    
    // Update is called once per frame
    void Update () {
    
        if (isStartS)
        {
            //每隔2秒调用一次,看一下有没有二维码,识别扫描二维码
            interval += Time.deltaTime;
            if (interval >= 2f)
            {
                ScanQRCode();//每隔3秒
                interval = 0;
            }
    
        }
    }
    //开始扫描识别二维码
    public void StartScanQRCode()
    {
        //开启摄像头
        WebCamDevice[] devices = WebCamTexture.devices;
        string deviceName = devices[0].name;
        webCamTexture = new WebCamTexture(deviceName, 400, 300);
        cameraTexture.texture = webCamTexture;
        webCamTexture.Play();
        isStartS = true;
    }
    //开始创建一个二维码
    public void StartCreateQRCode()
    {
        ShowQRCode("非子萧", 256, 256);//显示二维码的大小
        // QRCodeTexture.texture = CreateQRCodeTexture("xx", 512, 512,true);//任意大小,创建并保存二维码,但不支持中文???
    }
    
    //扫描二维码
    void ScanQRCode()
    {
        data = webCamTexture.GetPixels32();
        var result= barcodeReader.Decode(data,webCamTexture.width,webCamTexture.height);//识别,二维码
        if (result!=null)
        {
            Debug.Log(result.Text);
        }
    }
    //显示二维码
    void ShowQRCode(string str,int width,int height)
    {
        Texture2D t = new Texture2D(width, height); //创建一个空纹理贴图
        t.SetPixels32(CreateQRCode(str, width, height));//空图片的像素为创建的二维码
        t.Apply();
        //Debug.Log("创建一个空纹理贴图,贴图为二维码");
    
        QRCodeTexture.texture = t;//
    }
    //创建二维码(只能生成256,256)返回 Color32[]格式 formatStr=二维码显示的内容
    Color32[] CreateQRCode(string formatStr,int width,int height)
    {
        ZXing.QrCode.QrCodeEncodingOptions options = new ZXing.QrCode.QrCodeEncodingOptions();//二维码选项
        options.CharacterSet = "UTF-8";//设置字符编码,否则中文不能显示
        options.Width = width;//二微码宽
        options.Height = width;//二微码高
        options.Margin = 1;//二微码距离边缘的空白
        barcodeWriter = new BarcodeWriter{ Format = BarcodeFormat.QR_CODE,Options=options};//创建二维码
    
        // Debug.Log("创建二维码");
    
        return barcodeWriter.Write(formatStr);
    }
    //创建二维码(任何大小))返回 Color32[]格式 formatStr=二维码显示的内容
    Color32[] CreateQRCode2(string textForEncoding, int width, int height)
    {
        //不能识别中文??????
        ZXing.Common.BitMatrix matrix = new MultiFormatWriter().encode(textForEncoding,
                BarcodeFormat.QR_CODE, width, height);
        Color32[] pixels = new Color32[width * height];
        //
        // 下面这里按照二维码的算法,逐个生成二维码的图片, 
        // 两个for循环是图片横列扫描的结果  
        Color32 black = new Color32(255, 255, 255, 255);
        Color32 white = new Color32(0, 0, 0, 255);
        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                if (matrix[x, y])
                {
                    pixels[y * width + x] = white;// 0xff000000;
                }
                else
                {
                    pixels[y * width + x] = black;// 0xffffffff;
                }
            }
        }
       return pixels;
    }
    /// <summary>
    /// 生成二维码纹理
    /// </summary>
    /// <param name="textForEncoding">二维码的内容</param>
    /// <param name="width">二维码大宽</param>
    /// <param name="height">二维码高</param>
    /// <param name="issave">是否保存二维码</param>
    /// <returns></returns>
    public Texture2D CreateQRCodeTexture(string textForEncoding, int width, int height, bool issave = false)
    {
        if (width > 512 && height > 512)
        {
            //保存的二维码图片太大,消耗CPU性能
            Debug.LogError("Do not save too big, it will consume cpu performance so much!! ");
        }
        string fullpath = QRTextureSavedPath + "/" + textForEncoding + ".png";
        //Debug.LogError("fullpath: "+ fullpath);
        //先判断文件夹下面有没有这个文件
        Texture2D encoded = GetAlreadySavePng(fullpath, width, height);
        if (encoded != null)
        {
            return encoded;
        }
        else //如果没有要重新创建并视issave保存
        {
            encoded = new Texture2D(width, height);
            var color32 = CreateQRCode2(textForEncoding, width, height);
            encoded.SetPixels32(color32);
            encoded.Apply();
            if (issave)//保存二维码图片
            {
               // if (!Application.isEditor || m_IsEditorSaveTexture)
                    {
                        var bytes = encoded.EncodeToPNG();//把二维码转成byte数组,然后进行输出保存为png图片就可以保存下来生成好的二维码
                    if (!System.IO.Directory.Exists(QRTextureSavedPath)) //创建生成目录,如果不存在则创建目录
                    {
                        Debug.Log("CreateDirectory: " + QRTextureSavedPath);
                        System.IO.Directory.CreateDirectory(QRTextureSavedPath);
                    }
                    System.IO.File.WriteAllBytes(fullpath, bytes);//保存二维码图片
                    UnityEditor.AssetDatabase.Refresh();//刷新,使刚创建的图片立刻导入。接下来才可以被使用
                    }
            }
        }
        return encoded;
    }
    //取得保存生成的二维码图片
    private Texture2D GetAlreadySavePng(string fullpath, int width, int height)
    {
        Texture2D ret = null;
        byte[] bytes = null;
        if (System.IO.File.Exists(fullpath))
        {
            bytes = System.IO.File.ReadAllBytes(fullpath);
            if (bytes != null)
            {
                ret = new Texture2D(width, height);
                ret.LoadImage(bytes, true);
            }
        }
        return ret;
    }
    

    }

    相关文章

      网友评论

        本文标题:ZXing生成保存,识别二维码

        本文链接:https://www.haomeiwen.com/subject/wqxtvxtx.html