Xamarin  

Xamarin Android: Create Your Own Android Camera App

Step 1- Open Visual Studio->New Project->Templates->Visual C#->Android->Blank app.

Select Blank app. Give project name and project location.

Blank App

Step 2- Open Solution Explorer-> Project Name->Resources->Layout->Main.axml. Click Open Design View.

Step 3- Go to Tool bar, select button and ImageView. Drag and drop Main.xaml design view.

CODE
Step 4- Go to Solution Explorer-> Project Name. Right click to Add->Class, followed by opening new Dialog box. This dialog box is required to select the class and give name for BitmapHelpers.cs.

Class

Step 5- Open Solution Explorer-> Project Name->Resources-> BitmapHelpers.cs. This class is reducing the image size and recycling the memory. It will be used to calculate an image ratio.

Code

C# Code

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using Android.App;  
  6. using Android.Content;  
  7. using Android.OS;  
  8. using Android.Runtime;  
  9. using Android.Views;  
  10. using Android.Widget;  
  11. using Android.Graphics;  
  12. using Android.Graphics.Drawables;  
  13. namespace Camera {  
  14.     public static class BitmapHelpers {  
  15.         /// This method will recyle the memory help by a bitmap in an ImageView  
  16.         public static void RecycleBitmap(this ImageView imageView) {  
  17.                 if (imageView == null) {  
  18.                     return;  
  19.                 }  
  20.                 Drawable toRecycle = imageView.Drawable;  
  21.                 if (toRecycle != null) {  
  22.                     ((BitmapDrawable) toRecycle).Bitmap.Recycle();  
  23.                 }  
  24.             }  
  25.             /// Load the image from the device, and resize it to the specified dimensions.  
  26.         public static Bitmap LoadAndResizeBitmap(this string fileName, int width, int height) {  
  27.             // First we get the the dimensions of the file on disk  
  28.             BitmapFactory.Options options = new BitmapFactory.Options {  
  29.                 InPurgeable = true,  
  30.                     InJustDecodeBounds = true  
  31.             };  
  32.             BitmapFactory.DecodeFile(fileName, options);  
  33.             // Next we calculate the ratio that we need to resize the image by  
  34.             // in order to fit the requested dimensions.  
  35.             int outHeight = options.OutHeight;  
  36.             int outWidth = options.OutWidth;  
  37.             int inSampleSize = 1;  
  38.             if (outHeight > height || outWidth > width) {  
  39.                 inSampleSize = outWidth > outHeight ? outHeight / height : outWidth / width;  
  40.             }  
  41.             // Now we will load the image and have BitmapFactory resize it for us.  
  42.             options.InSampleSize = inSampleSize;  
  43.             options.InJustDecodeBounds = false;  
  44.             Bitmap resizedBitmap = BitmapFactory.DecodeFile(fileName, options);  
  45.             return resizedBitmap;  
  46.         }  
  47.     }  
  48. }  
Step 6- Open Solution Explorer-> Project Name->Resources-> MainActicity.cs. Add NameSpace, given below-
  1. using Android.Provider;  
  2. using Java.IO;  
  3. using Android.Graphics;  
  4. using Android.Content.PM;  
  5. using Uri = Android.Net.Uri;  
  6. using System.Collections.Generic;  
Step 7- First, declare the button, image variables and open Oncreate(). The code is given below-

Code
C# Code
  1. Button BtnTakeImg;  
  2. ImageView ImgView;  
  3. public static File _file;  
  4. public static File _dir;  
  5. protected override void OnCreate(Bundle bundle)  
  6. {  
  7.     base.OnCreate(bundle);  
  8.     // Set our view from the "main" layout resource  
  9.     SetContentView(Resource.Layout.Main);  
  10.     if (IsThereAnAppToTakePictures()) {  
  11.         CreateDirectoryForPictures();  
  12.         BtnTakeImg = FindViewById < Button > (Resource.Id.btntakepicture);  
  13.         ImgView = FindViewById < ImageView > (Resource.Id.ImgTakeimg);  
  14.         BtnTakeImg.Click += TakeAPicture;  
  15.     }  
  16. }  
Step 8- We create IsThereAnAppToTakePictures() and CreateDirectoryForPictures().

Step 9- Here, CreateDirectoryForPictures () is to be used to create separate folder for our image. IsThereAnAppToTakePictures() is redirecting to Android Camera path.

Code
Code

C# Code
  1. private void CreateDirectoryForPictures() {  
  2.     _dir = new File(Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures), "C#Corner");  
  3.     if (!_dir.Exists()) {  
  4.         _dir.Mkdirs();  
  5.     }  
  6. }  
  7. private bool IsThereAnAppToTakePictures() {  
  8.     Intent intent = new Intent(MediaStore.ActionImageCapture);  
  9.     IList < ResolveInfo > availableActivities = PackageManager.QueryIntentActivities(intent, PackageInfoFlags.MatchDefaultOnly);  
  10.     return availableActivities != null && availableActivities.Count > 0;  
  11. }  
  12. private void TakeAPicture(object sender, EventArgs eventArgs) {  
  13.     Intent intent = new Intent(MediaStore.ActionImageCapture);  
  14.     _file = new File(_dir, string.Format("Image_{0}.jpg", Guid.NewGuid()));  
  15.     intent.PutExtra(MediaStore.ExtraOutput, Uri.FromFile(_file));  
  16.     StartActivityForResult(intent, 102);  
  17. }  
  18. protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) {  
  19.     if (requestCode == 102 && resultCode == Result.Ok) {  
  20.         // make it available in the gallery  
  21.         Intent mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);  
  22.         Uri contentUri = Uri.FromFile(_file);  
  23.         mediaScanIntent.SetData(contentUri);  
  24.         SendBroadcast(mediaScanIntent);  
  25.         //Converstion Image Size  
  26.         int height = ImgView.Height;  
  27.         int width = Resources.DisplayMetrics.WidthPixels;  
  28.         using(Bitmap bitmap = _file.Path.LoadAndResizeBitmap(width, height)) {  
  29.             //View ImageView  
  30.             ImgView.RecycleBitmap();  
  31.             ImgView.SetImageBitmap(bitmap);  
  32.             //Upload Image in Database  
  33.         }  
  34.     }  
  35. }  
Step 10-Finally, give the permission AndroidManifest.XML, stated below- 
  1. <uses-permission android:name="android.permission.CAMERA" />  
  2. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />  
  3. <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />   
Step 11- Press F5 or build and run the Application.
 


Step 12-
 After running the Application, go and check gallery. See the last captured picture. Finally, we successfully created Xamarin Android, using our own camera app and showing Imageview last captured image.