Search code examples
c#unity-game-enginezxing

Using ZXing in Unity to locate QRcode's Position Pattern


As the title, i want to use locate three Position Pattern.

Example

I want to know how to get the x y position of those pattern when I got a new QR code from a webcamtexture.
How should I implement this is Unity(C#)?


Solution

  • Use the following code for decoding ZXing dll.

    private WebCamTexture camTexture;
    private Rect screenRect;
    void Start()
    {
        screenRect = new Rect(0, 0, Screen.width, Screen.height);
        camTexture = new WebCamTexture();
        camTexture.requestedHeight = Screen.height;
        camTexture.requestedWidth = Screen.width;
        if (camTexture != null)
        {
            camTexture.Play();
        }
    }
    
    void OnGUI()
    {
        // drawing the camera on screen
        GUI.DrawTexture(screenRect, camTexture, ScaleMode.ScaleToFit);
        // do the reading — you might want to attempt to read less often than you draw on the screen for performance sake
        try
        {
            IBarcodeReader barcodeReader = new BarcodeReader();
            // decode the current frame
            var result = barcodeReader.Decode(camTexture.GetPixels32(), camTexture.width, camTexture.height);
            if (result != null)
            {
                Debug.Log("DECODED TEXT FROM QR: " +result.Text);
            }
            ResultPoint[] point = result.ResultPoints;
            Debug.Log("X: " + point[0].X + " Y: " + point[1].Y);
        }
        catch (Exception ex) { Debug.LogWarning(ex.Message); }
    }
    

    I had taken reference from ZXing dll link. It also has qr code generator in readme. Go through readme. Its almost same just ResultPoint[] point = result.ResultPoints; has been added to it. This gives the position of the 3 corners of image. Obviously you will need to add the ZXing.dll in plugins folder in the Assets. Hope this helps to get the result.