UnityでQRコードを作る

ZXingを使ってQRコードをUnityで読み書きしよう。

Negipoyoc

はじめに

UnityでQRコードを作れると便利な時もあります。

例えばVRアプリの展示などで、ユーザが描いた絵などの写真を体験終了時などに自動でサーバにアップロードする。その後ユーザに対して、その画像へのURLをQRコードで渡せるとお土産として渡すことができます。

展示の魅力をより引き立たせる効果が狙えますね。

用意するもの

  • ZXing.dll
  • Unity(今回は5.6.1f1)

準備

①ZXing.dllをダウンロードする。 https://zxingnet.codeplex.com/
②Unityプロジェクト内のAssets/Plugins以下にdllを入れる。

サンプルコード

以下。

Util class

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

public class QRCodeUtil
{
    /// <summary>
    /// QRコード読み取り)(返り文字列が-1の場合は、読み込めていない)
    /// </summary>
    /// <param name="cameraTexture">Camera texture.</param>
    public Result Read(WebCamTexture cameraTexture)
    {
        var reader = new BarcodeReader();
        var color = cameraTexture.GetPixels32();
        var width = cameraTexture.width;
        var height = cameraTexture.height;
        var result = reader.Decode(color, width, height);

        return result;
    }


    /// <summary>
    /// QRコード作成
    /// </summary>
    /// <param name="inputString">QRコード生成元の文字列</param>
    /// <param name="textture">QRの画像がここに入る</param>
    public Texture2D Create(string inputString, int width, int height)
    {
        var texture = new Texture2D(width, height);
        var qrCodeColors = Write(inputString, width, height);
        texture.SetPixels32(qrCodeColors);
        texture.Apply();

        return texture;
    }


    private Color32[] Write(string content, int width, int height)
    {
        var writer = new BarcodeWriter
        {
            Format = BarcodeFormat.QR_CODE,
            Options = new QrCodeEncodingOptions
            {
                Height = height,
                Width = width
            }
        };

        return writer.Write(content);
    }
}

上のコードを利用して実際に使用する時

        var qrUtil = new QRCodeUtil();
        var qrTexture = qrUtil.Create("name", 256 , 256);
        var qrSprite = Sprite.Create(qrTexture, new Rect(0, 0, 256 , 256),Vector2.zero);
        image.sprite = qrSprite;

※なぜかWidthとHeightは2の倍数じゃないとQRコード生成が正しく動かなかった。

おまけ

生成したQRコードをJPGとして保存する。

        var qrTexture = qrUtil.Create("name", 256 , 256);
        var b = qrTexture.EncodeToJPG();
        //StreamingAssets以下にname.jpgとして保存する時。
        File.WriteAllBytes(Application.streamingAssetsPath + "/" + "name.jpg", b);