生成二维码

作者:追风剑情 发布于:2019-10-29 16:26 分类:Unity3d

一、下载 ThoughtWorks.QRCode.dll放到Unity工程的Plugins目录下
1111.png
百度网盘下载 提取码 s786
PS: System.ComponentModel.dll和System.Drawing.dll在Unity的安装目录下就可以找到。

二、封装一个生成二维码的辅助类

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using UnityEngine;
using ThoughtWorks.QRCode.Codec;

/// <summary>
/// 生成二维码辅助类 (仅考虑了Windows平台)
/// 需要下载 ThoughtWorks.QRCode.dll
/// </summary>
public sealed class QRCodeHelper
{
    /// <summary>
    /// 创建二维码Texture (Unity接口)
    /// </summary>
    /// <param name="content"></param>
    /// <param name="savePath"></param>
    /// <param name="fileName"></param>
    /// <returns></returns>
    public static Texture2D CreateQRcodeTexture(string content, string savePath, string fileName = "qrcode")
    {
        Bitmap bitmap = CreateQRCode(content);
        int width = bitmap.Width;
        int height = bitmap.Height;
        MemoryStream ms = new MemoryStream();
        /*
         * 当程序发布后需要手动拷贝{Unity安装目录}\Editor\Data\MonoBleedingEdge\lib\mono\4.5\System.Drawing.dll
         * 到{项目发布目录}\XXXXX_Data\Managed\System.Drawing.dll(替换此dll),否则Save()方法会报错。
         */
        bitmap.Save(ms, bitmap.RawFormat);
        byte[] bytes = ms.ToArray();

        // 保存到磁盘则不需要替换System.Drawing.dll
        //bitmap.Save("tmp.png", ImageFormat.Png);
        //byte[] bytes = File.ReadAllBytes("tmp.png");

        Texture2D tex = new Texture2D(width, height, TextureFormat.RGBA32, false);
        tex.LoadImage(bytes);
        tex.Apply();

        return tex;
    }

    /// <summary>
    /// 创建并保存二维码图片
    /// </summary>
    /// <param name="content"></param>
    /// <param name="savePath"></param>
    /// <param name="fileName"></param>
    public static void CreateQRcode(string content, string savePath, string fileName="qrcode")
    {
        Bitmap bitmap = CreateQRCode(content);
        SaveQRCode(bitmap, savePath, fileName);
    }

    /// <summary>
    /// 创建二维码 (C#接口)
    /// </summary>
    /// <param name="content">内容</param>
    /// <returns></returns>
    public static Bitmap CreateQRCode(string content)
    {
        try
        {
            QRCodeEncoder qrEncoder = new QRCodeEncoder();
            //二维码类型
            qrEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
            //二维码尺寸
            qrEncoder.QRCodeScale = 4;
            //二维码版本
            qrEncoder.QRCodeVersion = 7;
            //二维码容错程度
            qrEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
            //字体与背景颜色
            qrEncoder.QRCodeBackgroundColor = System.Drawing.Color.White;
            qrEncoder.QRCodeForegroundColor = System.Drawing.Color.Black;
            //UTF-8编码类型
            Bitmap qrcode = qrEncoder.Encode(content, Encoding.UTF8);

            return qrcode;
        }
        catch (Exception)
        {
            return null;
        }
    }

    /// <summary>
    /// 保存二维码 (C#接口)
    /// </summary>
    /// <param name="QRCode">二维码图片</param>
    /// <param name="SavePath">保存路径</param>
    /// <param name="QRCodeName">图片名称</param>
    public static void SaveQRCode(Bitmap QRCode, string SavePath, string QRCodeName)
    {
        if (!Directory.Exists(SavePath))
        {
            Directory.CreateDirectory(SavePath);
        }
        QRCode.Save(Path.Combine(SavePath, QRCodeName + ".png"), ImageFormat.Png);

        QRCode.Dispose();
    }
}

测试效果

222.png

如果将Bitmap保存到内存流,必须用{Unity安装目录}下的System.Drawing.dll替换{发布目录}下的同名dll,否则调用Bitmap.Save()方法时会报如下错:

NullReferenceException: Object reference not set to an instance of an object
  at System.Drawing.ComIStreamMarshaler+ManagedToNativeWrapper..cctor () [0x00049] in <868bfedd9fd649b7a5aa185d8ce8619b>:0 
Rethrow as TypeInitializationException: The type initializer for 'ManagedToNativeWrapper' threw an exception.
  at System.Drawing.ComIStreamMarshaler.MarshalManagedToNative (System.Object managedObj) [0x00000] in <868bfedd9fd649b7a5aa185d8ce8619b>:0 
  at (wrapper managed-to-native) System.Drawing.GDIPlus.GdipSaveImageToStream(System.Runtime.InteropServices.HandleRef,
System.Runtime.InteropServices.ComTypes.IStream,System.Guid&,System.Runtime.InteropServices.HandleRef)

  at System.Drawing.Image.Save (System.IO.Stream stream, System.Drawing.Imaging.ImageCodecInfo encoder, System.Drawing.Imaging.EncoderParameters encoderParams) [0x0007e] in <868bfedd9fd649b7a5aa185d8ce8619b>:0 
  at System.Drawing.Image.Save (System.IO.Stream stream, System.Drawing.Imaging.ImageFormat format) [0x00029] in <868bfedd9fd649b7a5aa185d8ce8619b>:0 
  at (wrapper remoting-invoke-with-check) System.Drawing.Image.Save(System.IO.Stream,System.Drawing.Imaging.ImageFormat)

标签: Unity3d

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号