Generate Barcode and QR Code in Xamarin Android
Tags: barcodeinxamarina, qrcodeinxamarina
Published: 2019-12-22 15:25:55

---
title: Generate Barcode and QR Code in Xamarin Android
published: true
date: 2019-08-15 12:31:00 UTC
tags: Barcode in Xamarin A,QR Code in Xamarin A
canonical_url: https://logeshpalani.blogspot.com/2019/08/barcode-and-qr-code-generator-in.html
---

  

Introduction

  

           In this article, we can discuss how to generate 1D and 2D Barcode in Xamarin Android application. Here basic requirement to generate Barcode or QR Code, we need to get some information form user like what message you want to convert, Code format, size of the bitmap. There is no default library for this. so, we need to install a plugin for this. Just write a few lines of code to generate 1D and 2D Code. The Barcode has a different format but I demonstrate some few code formats - Code 39, Code 128, AZTEC and QR Code. 

  

  

Android Output:

  

[![](https://1.bp.blogspot.com/-n7Nwb788E_g/XVVC1DJnMVI/AAAAAAAAO-g/c2G4NVXsPoAy0rspbWHIZn5QXphMtI3gACLcBGAs/s320/ezgif.com-optimize.gif)](https://1.bp.blogspot.com/-n7Nwb788E_g/XVVC1DJnMVI/AAAAAAAAO-g/c2G4NVXsPoAy0rspbWHIZn5QXphMtI3gACLcBGAs/s1600/ezgif.com-optimize.gif)

  

  

Let’s start 😊

  

Step 1:

  

     Create can create Xamarin.Android Application by going to Visual Studio New Project >> Android App click next.

  

[![](https://1.bp.blogspot.com/-v_4_hEiOr_8/XVUUHWLD0ZI/AAAAAAAAO-Q/Ndqa5J47Gl0FtbeZwqzMjzV0UR0mhcdpwCLcBGAs/s400/Screen%2BShot%2B2019-08-09%2Bat%2B7.16.52%2BPM.png)](https://1.bp.blogspot.com/-v_4_hEiOr_8/XVUUHWLD0ZI/AAAAAAAAO-Q/Ndqa5J47Gl0FtbeZwqzMjzV0UR0mhcdpwCLcBGAs/s1600/Screen%2BShot%2B2019-08-09%2Bat%2B7.16.52%2BPM.png)

  
Here gives a project name, organization name, app compatibility, and app theme, then click Create.

  

[![](https://1.bp.blogspot.com/-YmHhuTlUF6U/XVUUHRXVs9I/AAAAAAAAO-M/lOSn19Yk0qc7Ee4Bpe5koTh3SynLAonVwCLcBGAs/s320/Screen%2BShot%2B2019-08-09%2Bat%2B7.17.08%2BPM.png)](https://1.bp.blogspot.com/-YmHhuTlUF6U/XVUUHRXVs9I/AAAAAAAAO-M/lOSn19Yk0qc7Ee4Bpe5koTh3SynLAonVwCLcBGAs/s1600/Screen%2BShot%2B2019-08-09%2Bat%2B7.17.08%2BPM.png)

  

  

  

Step 2:

     After project creation, first we need to install a plugin for this by going to Solution Explorer >> right-click Packages and select Add packages, then new windows will appear, here right-side top search ZXing.Net plugin and add this package.

  

[![](https://1.bp.blogspot.com/-z3fqXoMTapo/XVUUHSJxIAI/AAAAAAAAO-U/cDDxKaQvnKE2_3vq2y3SAbIyW3OMfWDYwCEwYBhgL/s400/Screen%2BShot%2B2019-08-09%2Bat%2B6.15.02%2BPM.png)](https://1.bp.blogspot.com/-z3fqXoMTapo/XVUUHSJxIAI/AAAAAAAAO-U/cDDxKaQvnKE2_3vq2y3SAbIyW3OMfWDYwCEwYBhgL/s1600/Screen%2BShot%2B2019-08-09%2Bat%2B6.15.02%2BPM.png)

  

  

Step 3:

     Now, let’s coding. First open content\_main.xml. For that, go to Solution Explorer >> Resource >> Layout >> double click to open content\_main.xml. add the following given code to this file.

  

  

| 
```
1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
```
 | 
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout\_width="match\_parent"
android:layout\_height="match\_parent"
app:layout\_behavior="@string/appbar\_scrolling\_view\_behavior"
tools:showIn="@layout/activity\_main">
<TextView
android:id="@+id/txtChooseStatic"
android:layout\_width="fill\_parent"
android:layout\_height="wrap\_content"
android:layout\_marginTop="10dp"
android:layout\_alignParentTop="true"
android:text="Choose Encoding Method" />
<Spinner
android:id="@+id/spinner"
android:layout\_width="fill\_parent"
android:layout\_marginTop="10dp"
android:layout\_height="wrap\_content"
android:layout\_below="@+id/txtChooseStatic"
android:prompt="@string/action\_choose"/>
<EditText
android:id="@+id/plain\_text\_input"
android:layout\_height="wrap\_content"
android:layout\_width="match\_parent"
android:layout\_margin="10dp"
android:layout\_below="@+id/spinner"
android:hint="Type Message to Convert"
android:inputType="text"/>
<ImageView
android:layout\_centerHorizontal="true"
android:layout\_marginTop="10dp"
android:id="@+id/barcodeImage"
android:layout\_below="@+id/plain\_text\_input"
android:layout\_width="wrap\_content"
android:layout\_height="wrap\_content"/>
<Button
android:id="@+id/generate"
android:background="#000000"
android:textColor="#ffffff"
android:layout\_centerHorizontal="true"
android:layout\_width="wrap\_content"
android:padding="10dp"
android:layout\_marginTop="10dp"
android:layout\_below="@+id/barcodeImage"
android:layout\_height="wrap\_content"
android:textSize="15dp"
android:text="Generate Code"/>

</RelativeLayout>

```
 |

  

Step 4:

    Next open, MainActivity.cs and add the following code to generate bar code. For that, open Solution Explorer >> MainActivity.cs. This page code gives below.

  
  

| 
```
1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
```
 | 
```
using System;
using System.IO;
using Android.App;
using Android.Content.PM;
using Android.Graphics;
using Android.OS;
using Android.Runtime;
using Android.Support.Design.Widget;
using Android.Support.V4.App;
using Android.Support.V4.Content;
using Android.Support.V7.App;
using Android.Views;
using Android.Widget;
using ZXing;
using ZXing.Common;

namespace BarCodeGenerator
{
    [Activity(Label = "@string/app\_name", Theme = "@style/AppTheme.NoActionBar", MainLauncher = true)]
public class MainActivity : AppCompatActivity
    {
private TextView txtMessage;
private string message;
private static int size = 660;
private static int small\_size = 264;
private Spinner spinnerValue;
private string CodeType;

protected override void OnCreate(Bundle savedInstanceState)
        {
base.OnCreate(savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            SetContentView(Resource.Layout.activity\_main);

            Android.Support.V7.Widget.Toolbar toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
            SetSupportActionBar(toolbar);

            ImageView image = FindViewById<ImageView>(Resource.Id.barcodeImage);
            Button btnGenerate = FindViewById<Button>(Resource.Id.generate);
            txtMessage = FindViewById<TextView>(Resource.Id.plain\_text\_input);
            spinnerValue = FindViewById<Spinner>(Resource.Id.spinner);
            FloatingActionButton fab = FindViewById<FloatingActionButton>(Resource.Id.fab);

var adapter = ArrayAdapter.CreateFromResource(this, Resource.Array.selected\_Code, Android.Resource.Layout.SimpleSpinnerItem);
            adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
            spinnerValue.Adapter = adapter;
            spinnerValue.ItemSelected += new EventHandler<AdapterView.ItemSelectedEventArgs>(SpinnerItemSelect);
            fab.Click += FabOnClick;

            btnGenerate.Click += delegate
            {
string[] PERMISSIONS =
                {
"android.permission.READ\_EXTERNAL\_STORAGE",
"android.permission.WRITE\_EXTERNAL\_STORAGE"
                };

var permission = ContextCompat.CheckSelfPermission(this, "android.permission.WRITE\_EXTERNAL\_STORAGE");
var permissionread = ContextCompat.CheckSelfPermission(this, "android.permission.READ\_EXTERNAL\_STORAGE");

if (permission != Permission.Granted && permissionread != Permission.Granted)
                    ActivityCompat.RequestPermissions(this, PERMISSIONS, 1);

try
                {
if (permission == Permission.Granted && permissionread == Permission.Granted)
                    {
                        BitMatrix bitmapMatrix = null;
                        message = txtMessage.Text.ToString();

switch (CodeType)
                        {
case "QR Code":
                                bitmapMatrix = new MultiFormatWriter().encode(message, BarcodeFormat.QR\_CODE, size, size);
break;
case "PDF 417":
                                bitmapMatrix = new MultiFormatWriter().encode(message, BarcodeFormat.PDF\_417, size, small\_size);
break;
case "CODE 128":
                                bitmapMatrix = new MultiFormatWriter().encode(message, BarcodeFormat.CODE\_128, size, small\_size);
break;
case "CODE 39":
                                bitmapMatrix = new MultiFormatWriter().encode(message, BarcodeFormat.CODE\_39, size, small\_size);
break;
case "AZTEC":
                                bitmapMatrix = new MultiFormatWriter().encode(message, BarcodeFormat.AZTEC, size, small\_size);
break;
                        }

var width = bitmapMatrix.Width;
var height = bitmapMatrix.Height;
int[] pixelsImage = new int[width \* height];

for (int i = 0; i < height; i++)
                        {
for (int j = 0; j < width; j++)
                            {
if (bitmapMatrix[j, i])
                                    pixelsImage[i \* width + j] = (int)Convert.ToInt64(0xff000000);
else
                                    pixelsImage[i \* width + j] = (int)Convert.ToInt64(0xffffffff);

                            }
                        }

                        Bitmap bitmap = Bitmap.CreateBitmap(width, height, Bitmap.Config.Argb8888);
                        bitmap.SetPixels(pixelsImage, 0, width, 0, 0, width, height);

var sdpath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
var path = System.IO.Path.Combine(sdpath, "logeshbarcode.jpg");
var stream = new FileStream(path, FileMode.Create);
                        bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, stream);
                        stream.Close();

                        image.SetImageBitmap(bitmap);
                    }
else
                    {
                        Console.WriteLine("No Permission");
                    }
                }
catch (Exception ex)
                {
                    Console.WriteLine($"Exception {ex} ");
                }
            };
        }

private void SpinnerItemSelect(object sender, AdapterView.ItemSelectedEventArgs e)
        {
            Spinner spinner = (Spinner)sender;
            CodeType = (string)spinner.GetItemAtPosition(e.Position);
        }

public override bool OnCreateOptionsMenu(IMenu menu)
        {
            MenuInflater.Inflate(Resource.Menu.menu\_main, menu);
return true;
        }

public override bool OnOptionsItemSelected(IMenuItem item)
        {
int id = item.ItemId;
if (id == Resource.Id.action\_settings)
            {
return true;
            }

return base.OnOptionsItemSelected(item);
        }

private void FabOnClick(object sender, EventArgs eventArgs)
        {
            View view = (View)sender;
            Snackbar.Make(view, "Replace with your own action", Snackbar.LengthLong)
                .SetAction("Action", (Android.Views.View.IOnClickListener)null).Show();
        }
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
        {
            Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}

```
 |

  

  
   

Step 5:

  

         Finally, the application required storage read and write permission. For that, go to Solution Explorer >> Properties >> Open AndroidManifest.xml file. Check the Permissions of External Storage Read and Write Permission.

  

<!-- HTML generated using hilite.me -->  

| 
```
1
2
```
 | 
```
<uses-permission android:name="android.permission.WRITE\_EXTERNAL\_STORAGE" />
<uses-permission android:name="android.permission.READ\_EXTERNAL\_STORAGE" />

```
 |

  
  

Step 6:

  
  

        Now, press F5 to run the application. The Output like below.

  
  

[![](https://1.bp.blogspot.com/-n7Nwb788E_g/XVVC1DJnMVI/AAAAAAAAO-k/BRo53Y9YJUYKHyYW5AVwtHPovobNgVE8QCEwYBhgL/s320/ezgif.com-optimize.gif)](https://1.bp.blogspot.com/-n7Nwb788E_g/XVVC1DJnMVI/AAAAAAAAO-k/BRo53Y9YJUYKHyYW5AVwtHPovobNgVE8QCEwYBhgL/s1600/ezgif.com-optimize.gif)

  

  

  

Full Source Code [Here](https://github.com/logeshpalani98/QRCode-BarCodeGenerator)

  
  

Thank you. Suggestion to the command below.