二维码的生成与识别


将插件中zxing.unity.dll文件放入Unity工程中Plugins文件夹下,下载二维码插件 http://zxingnet.codeplex.com/

using UnityEngine;

using System.Collections;
using ZXing;
using UnityEngine.UI;
using ZXing.QrCode;
using System;


public class QuickMark : MonoBehaviour
{
public Color32[] data;
private bool isplay;
public RawImage cameraTexture;
public Text txt;
private WebCamTexture webCameraTexture;
private BarcodeReader barcodeReader;
private float timer = 0;
WebCamDevice[] devices;
public RawImage m_QRCode;//显示二维码
private BarcodeWriter m_barcodeWriter;
public void ShowFrame1()
{
StartCoroutine(ShowFrame());
}
IEnumerator ShowFrame()
{
barcodeReader = new BarcodeReader();
yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
if (Application.HasUserAuthorization(UserAuthorization.WebCam))
{
devices = WebCamTexture.devices;
string devicename = devices[0].name;
webCameraTexture = new WebCamTexture(devicename, 400, 300);
cameraTexture.texture = webCameraTexture;
webCameraTexture.Play();
isplay = true;
}
}
void Update()
{
if (isplay)
{
timer += Time.deltaTime;
if (timer > 0.5f) //0.5秒扫描一次
{
StartCoroutine(ScanQRcode());
timer = 0;
}
}
//ScreenChange();
}
/// <summary>
/// 扫描二维码
/// </summary>
/// <returns></returns>
IEnumerator ScanQRcode()
{
data = webCameraTexture.GetPixels32();
DecodeQR(webCameraTexture.width, webCameraTexture.height);
yield return new WaitForEndOfFrame();
}
/// <summary>
/// 破解二维码
/// </summary>
/// <param name="width"></param>
/// <param name="height"></param>
private void DecodeQR(int width, int height)
{
var br = barcodeReader.Decode(data, width, height);
if (br != null)
{
txt.text = "识别内容:" + br.Text;
}


}
#region 生成二维码
public void ShowQRCode1()
{
ShowQRCode(DateTime.Now.ToString(), 256, 256);
}
/// <summary>
/// 显示绘制的二维码
/// </summary>
/// <param name="s_formatStr">扫码信息</param>
/// <param name="s_width">码宽</param>
/// <param name="s_height">码高</param>m
public void ShowQRCode(string s_str, int s_width, int s_height)
{
//定义Texture2D并且填充
Texture2D tTexture = new Texture2D(s_width, s_height);
//绘制相对应的贴图纹理
tTexture.SetPixels32(GeneQRCode(s_str, s_width, s_height));
tTexture.Apply();
//赋值贴图
m_QRCode.texture = tTexture;
}
/// <summary>
/// 返回对应颜色数组
/// </summary>
/// <param name="s_formatStr">扫码信息</param>
/// <param name="s_width">码宽</param>
/// <param name="s_height">码高</param>
Color32[] GeneQRCode(string s_formatStr, int s_width, int s_height)
{
//设置中文编码格式,否则中文不支持
QrCodeEncodingOptions tOptions = new QrCodeEncodingOptions();
tOptions.CharacterSet = "UTF-8";
//设置宽高
tOptions.Width = s_width;
tOptions.Height = s_height;
//设置二维码距离边缘的空白距离
tOptions.Margin = 3;
//重置申请写二维码变量类   (参数为:码格式(二维码、条形码...)    编码格式(支持的编码格式)    )
m_barcodeWriter = new BarcodeWriter { Format = BarcodeFormat.QR_CODE, Options = tOptions };
//将咱们需要隐藏在码后面的信息赋值上
return m_barcodeWriter.Write(s_formatStr);
}
#endregion
}

猜你喜欢

转载自blog.csdn.net/qq_36215526/article/details/79970068