How i can generate QR code with logo on Unity3D?

2.8k views Asked by At

I want to generate QR code with logo like this:

Environment: Unity3D C#

I try to write code by examples from Internet.

private Texture2D GenerateBarcode(string data, BarcodeFormat format, int width, int height)
{
        var encodeOptions = new EncodingOptions
        {
            Height = height,
            Width = width,
            Margin = 0,
            PureBarcode = false
        };
        encodeOptions.Hints.Add(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);

        BarcodeWriter writer = new BarcodeWriter
        {
            Format = BarcodeFormat.QR_CODE,
            Options = encodeOptions
        };

        Color32[] pixels = writer.Write(text);
        Texture2D tex = new Texture2D(width, height);
        tex.SetPixels32(pixels);
        tex.Apply();
        return tex;
}

Q1: How i can change fill color the QR code from black color to the green color?

Q2: How i can change "black squares" on the sides of the QR code to another similiar figuare?

Please, help. I have no idea what i need did .

A1: Answer from derHugo


    for (var i = 0; i < pixels.Length; i++){
          var pixel = pixels[i];
                if (pixel.r == 0 && pixel.g == 0 && pixel.b == 0)
                {
                    pixel = Color.green;
                }
                else {
                    pixel = Color.white;
                }
                pixels[i] = pixel;
    }

1

There are 1 answers

1
derHugo On

To question one: Simply iterate over the pixels and tint the black ones with green instead like

Color32[] pixels = writer.Write(text);

for(var i=0; i<pixels.Length; i++)
{
    var pixel = pixels[i];
    if(pixel.r == 0 && pixel.g == 0 && pixel.b == 0) continue;

    pixel = Color.black;
    pixels[i] = pixel;
}

Texture2D tex = new Texture2D(width, height);
tex.SetPixels32(pixels);
tex.Apply();

To question 2: There are a lot of similar question out there like e.g. Add custom image or text to QR code generated by ZXing.Net or also this post at least for the middle Logo. The principle for the edges would be basically the same: Overwrite according pixels with a custom image.