Search code examples
c#androidxamarinxamarin.formszxing

Problems Implementing a QR Code Generator with Xamarin Forms


I'm having some trouble with an implementation of the ZXing.Net.Mobile (Android) implementation in Xamarin Forms. I have the following class in my Android project which implements the IBarcodeWriter interface (which is in my Shared Project). The application isn't throwing any errors but it isn't showing an image when added into a stacklayout with DependencyService.Get<IBarcodeWriter> ().GetImage()

This is the class from my Droid project:

namespace SmartCart {

public class BarcodeGenerator : IBarcodeWriter
{
    public BarcodeGenerator () {}
    public Image image = new Image();
    public byte[] bitmapBytes;

    public String qrData (String s) {
        return s;
    }

    public void CreateBarcode () {

        image.Source = ImageSource.FromStream(() => 
            {
                var writer = new BarcodeWriter 
                {
                    Format = BarcodeFormat.QR_CODE,
                    Options = new EncodingOptions 
                    {
                        Height = 200,
                        Width = 600
                    }
                };

                var bitmapBytes = writer.Write ("Encode this to QRCode");
                MemoryStream ms = new MemoryStream(bitmapBytes);
                ms.Position = 0;
                return ms;

            });
    }

    public Image GetImage() {
        return image;
    }
}

Solution

  • We use following method to generate a QR-Code. (look at the bitmap.Compress row, maybe that solves your Problem):

    public byte[] GenerateQrImage(string content, int width, int height)
    {
        var options = new QrCodeEncodingOptions
        {
            Height = height,
            Width = width,
            Margin = 0,
            PureBarcode = true
        };
    
        var writer = new BarcodeWriter
        {
            Format = BarcodeFormat.QR_CODE,
            Options = options
        };
    
        // Generate bitmap
        var bitmap = writer.Write(content);
        if (bitmap != null)
        {
            // Get bytes from bitmap
            using (var stream = new MemoryStream())
            {
                bitmap.Compress(Bitmap.CompressFormat.Png, 100, stream);
                return stream.ToArray();
            }
        }
    
        return null;
    }
    

    Edit: It turns out, that the problem may be a wrong nuget package. use this package to generate the qr-code