unity 生成和识别二维码
方案一·:
1.识别
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using ZXing;
using UnityEngine.UI;
/// <summary>
/// 二维码扫描识别功能
/// </summary>
public class TestQRCodeScanning : MonoBehaviour
{
[Header("摄像机检测界面")]
public RawImage cameraTexture; //摄像机映射显示区域
private WebCamTexture webCamTexture; //摄像机映射纹理
public Text text; //用来显示扫描信息
//二维码识别类 BarcodeReader barcodeReader;//库文件的对象(二维码信息保存的地方)
/// <summary>
/// 开启摄像机和准备工作
/// </summary>
void DeviceInit()
{
//1、获取所有摄像机硬件
WebCamDevice[] devices = WebCamTexture.devices;
//2、获取第一个摄像机硬件的名称
string deviceName = devices[0].name; //手机后置摄像机
//3、创建实例化一个摄像机显示区域
webCamTexture = new WebCamTexture(deviceName, 400, 300);
//4、显示的图片信息
cameraTexture.texture = webCamTexture;
//5、打开摄像机运行识别
webCamTexture.Play();
//6、实例化识别二维码信息存储对象
barcodeReader = new BarcodeReader();
}
Color32[] data; //二维码图片信息以像素点颜色信息数组存放
/// <summary>
/// 识别摄像机图片中的二维码信息
/// 打印二维码识别到的信息
/// </summary>
void ScanQRCode()
{
//7、获取摄像机画面的像素颜色数组信息
data = webCamTexture.GetPixels32();
//8、获取图片中的二维码信息
Result result = barcodeReader.Decode(data, webCamTexture.width, webCamTexture.height);
//如果获取到二维码信息了,打印出来
if (result != null)
{
Debug.Log(result.Text);//===》==》===》 这是从二维码识别出来的信息
text.text = result.Text;//显示扫描信息
//扫描成功之后的处理:停止识别关闭相机
//IsScanning = false;
//webCamTexture.Stop();
}
}
/// <summary>
/// Start 初始化函数
/// </summary>
private void Start()
{
scanningButton.onClick.AddListener(ScanningButtonClick);
}
bool IsScanning = false;
float interval = 3; //扫描识别时间间隔
[SerializeField] Button scanningButton;
void ScanningButtonClick()
{
DeviceInit();
IsScanning = true;
}
private void Update()
{
if (IsScanning)
{
//每隔一段时间进行一次识别二维码信息
interval += Time.deltaTime;
if (interval >= 3)
{
interval = 0;
ScanQRCode(); //开始扫描
}
}
}
}
2.生成
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using ZXing;
//二维码的生成
public class TestQRCodeDraw : MonoBehaviour {
[Header("绘制好的二维码显示界面")]
public RawImage QRCode;
//二维码绘制类
BarcodeWriter barcodeWriter;
[SerializeField] Button drawbutton;
/// <summary>
/// 将制定字符串信息转换成二维码图片信息
/// </summary>
/// <param name="formatStr">要生产二维码的字符串信息</param>
/// <param name="width">二维码的宽度</param>
/// <param name="height">二维码的高度</param>
/// <returns>返回二维码图片的颜色数组信息</returns>
Color32[] GeneQRCode(string formatStr,int width,int height)
{
//绘制二维码前进行一些设置
ZXing.QrCode.QrCodeEncodingOptions options =
new ZXing.QrCode.QrCodeEncodingOptions();
//设置字符串转换格式,确保字符串信息保持正确
options.CharacterSet = "UTF-8";
//设置绘制区域的宽度和高度的像素值
options.Width = width;
options.Height = height;
//设置二维码边缘留白宽度(值越大留白宽度大,二维码就减小)
options.Margin = 1;
//实例化字符串绘制二维码工具
barcodeWriter = new BarcodeWriter {Format=BarcodeFormat.QR_CODE,Options=options };
//进行二维码绘制并进行返回图片的颜色数组信息
return barcodeWriter.Write(formatStr);
}
/// <summary>
/// 根据二维码图片信息绘制指定字符串信息的二维码到指定区域
/// </summary>
/// <param name="str">要生产二维码的字符串信息</param>
/// <param name="width">二维码的宽度</param>
/// <param name="height">二维码的高度</param>
/// <returns>返回绘制好的图片</returns>
Texture2D ShowQRCode(string str,int width,int height)
{
//实例化一个图片类
Texture2D t = new Texture2D(width, height);
//获取二维码图片颜色数组信息
Color32[] col32 = GeneQRCode(str, width, height);
//为图片设置绘制像素颜色信息
t.SetPixels32(col32);
//设置信息更新应用下
t.Apply();
//将整理好的图片信息显示到指定区域中
return t;
}
/// <summary>
/// 开始绘制指定信息的二维码
/// </summary>
/// <param name="formatStr"></param>
void DrawQRCode(string formatStr)
{
//注意:这个宽高度大小256不要变。不然生成的信息不正确
//256有可能是这个ZXingNet插件指定大小的绘制像素点数值
Texture2D t = ShowQRCode(formatStr, 256, 256);
//显示到UI界面的图片上
QRCode.texture = t;
}
public string QRCodeText = "二维码";
void DrawButtonClick()
{
DrawQRCode(QRCodeText);
}
private void Start()
{
drawbutton.onClick.AddListener(DrawButtonClick);
}
}
实例
识别二维码
脚本
using System;
using System.Collections;
using System.Threading;
using UnityEngine;
using UnityEngine.UI;
using ZXing;
public class QRCode : MonoBehaviour
{
public string LastResult;
public string CameraName;
public RawImage MyCameraTexture;
public int CameraIndex = 0;
public int CameraRequestedWidth = 1920;
public int CameraRequestedHeight = 1080;
public float ReadTime = 0.5f;
private Color32[] Data;
private WebCamTexture WebCameraTexture;
private bool IsStart = false;
//public RenderTexture QRRenderTexture;
private void Start()
{
//开启摄像头
StartCoroutine(CallCamera());
}
//调用摄像头
IEnumerator CallCamera()
{
//请求摄像头权限
yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
//是否取得使用摄像头权限
if (Application.HasUserAuthorization(UserAuthorization.WebCam))
{
//得到可用设备列表
WebCamDevice[] devices = WebCamTexture.devices;
//判断输入的CameraIndex是否合法
if (CameraIndex < 0)
{
Debug.LogError("CameraIndex 不可为负数");
yield break;
}
if (devices.Length <= CameraIndex)
{
Debug.LogError("Do not find Camera!");
}
else
{
CameraName = devices[CameraIndex].name;
WebCameraTexture = new WebCamTexture(devices[0].name, CameraRequestedWidth, CameraRequestedHeight, 25);
MyCameraTexture.texture = WebCameraTexture;
WebCameraTexture.Play(); //开始摄像
IsStart = true;
print(IsStart = true);
CameraRequestedWidth = WebCameraTexture.width;
CameraRequestedHeight = WebCameraTexture.height;
}
}
else
{
Debug.LogError("未获得系统授权!");
}
}
//开始调用摄像头
public void ShowCamera()
{
MyCameraTexture.enabled = true;
WebCameraTexture.Play();
}
//停止摄像头调用
public void HideCamera()
{
MyCameraTexture.enabled = false;
WebCameraTexture.Stop();
}
private void OnGUI()
{
GUI.Label(new Rect(260, 30, Screen.width, 20), "LastResult:" + LastResult);
if (GUI.Button(new Rect(0, 0, 200, 80), "Camera ON/OFF"))
{
if (WebCameraTexture.isPlaying)
HideCamera();
else
ShowCamera();
}
}
private void Update()
{
if (IsStart && MyCameraTexture.enabled)
{
Data = WebCameraTexture.GetPixels32();
//StartCoroutine(DecodeQR(WebCameraTexture.width, WebCameraTexture.height));
Thread t = new Thread(DecodeQR);
t.Start();
t.IsBackground = true;
}
}
private void DecodeQR()
{
//Debug.Log("DecodeQR()");
IsStart = false;
// 创建二维码读写器
var barcodeReader = new BarcodeReader { AutoRotate = true, TryHarder = true };
try
{
//Debug.Log("解");
// 对当前帧解码
Result result = barcodeReader.Decode(Data, CameraRequestedWidth, CameraRequestedHeight);
if (result != null)
{
LastResult = result.Text;
print("Read out:" + result.Text);
}
else
{
print("没有数据");
}
Data = null;
}
catch(Exception e)
{
Debug.LogError(e);
}
// 设置睡眠时间
Thread.Sleep((int)(ReadTime * 1000));
IsStart = true;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!