banner



How To Capture Camera Image In Kotlin

The ability to share capture and share images is one of the qualities that have propelled smartphone usages over the past decade. Multi-billion dollar tech franchises like Instagram and Pinterest accept thus been born. This ability tells us about ourselves as human beings, we love stories. Still stories don't just have to be put in words. We tin can as well utilise images and series of images called videos to convey our story.

If you are a programmer you need to comprise the ability to capture images or select already captured images and import them into your application. Then y'all can exercise all types of interesting things to these images.

Fortunately for us android sdk provides classes and APIs we tin use to provide this capability seamlessly into our application. So in this tutorial we acquire how to capture images via photographic camera and show them in an imageview. Alternatively, we will see how to select images from the gallery and return them on an imageview.

Example 1 – Kotlin Android Capture From Photographic camera or Select from ImagePicker

We are creating an app containing one activity. That action has an imageview and two buttons below it. When the user clicks the first button, we will initiate the Photographic camera via intent. So we can capture and prototype and that prototype volition exist rendered on an imageview inside our awarding. The second button allows usa to open up our system gallery. From the gallery we can select an image and have it rendered on our imageview.

Video Tutorial

Scout the video tutorial for more details and demo.

Stride i: Create our Project

Open app android studio and create a new project. Choose empty activity, choose Kotlin as our programming language. Make sure our app supports androidx artifacts. I will utilise Android API Level 15 as my minimum version.

Hither is my app level build.gradle:

          dependencies {     implementation fileTree(dir: 'libs', include: ['*.jar'])     implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"     testImplementation 'junit:junit:4.12'     implementation 'androidx.appcompat:appcompat:1.0.2'     implementation 'androidx.core:cadre-ktx:1.0.2'     implementation 'androidx.constraintlayout:constraintlayout:ane.one.iii' }                  

You can see there is no special dependency to be added.

Footstep 2 : Layouts

We will have only a single layout:

(a). activity_main.xml

          <?xml version="1.0" encoding="utf-viii"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"               android:orientation="vertical"               android:layout_width="match_parent"               android:gravity="center|acme"               android:layout_height="match_parent">     <TextView             android:id="@+id/headerTxt"             android:text="Camera and ImagePicker Tutorial"             android:background="@color/colorAccent"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:padding="5dp"             android:textAlignment="center"             android:textStyle="assuming"             android:textAppearance="@style/TextAppearance.AppCompat.Large"             android:textColor="@android:colour/white" />     <LinearLayout             android:layout_width="match_parent"             android:layout_height="300dp"             android:layout_marginTop="16dp"             android:gravity="middle"             android:groundwork="@android:color/darker_gray"             android:orientation="vertical">          <ImageView                 android:id="@+id/mImageView"                 android:layout_width="wrap_content"                 android:layout_height="wrap_content"                 android:layout_gravity="center_horizontal"                 android:contentDescription="Our Image"/>     </LinearLayout>      <LinearLayout             android:orientation="horizontal"             android:layout_width="match_parent"             android:layout_height="wrap_content">         <Button                 android:layout_weight="0.5"                 android:layout_width="0dp"                 android:layout_height="45dp"                 android:padding="5dp"                 android:text="Capture"                 android:layout_marginTop="10dp"                 android:textColor="@android:colour/white"                 android:background="@drawable/button_shape"                 android:id="@+id/btnCapture"/>          <Button                 android:layout_weight="0.5"                 android:layout_width="0dp"                 android:layout_height="45dp"                 android:padding="5dp"                 android:text="Choose"                 android:layout_marginTop="10dp"                 android:textColor="@android:colour/white"                 android:background="@drawable/button_shape"                 android:id="@+id/btnChoose"/>     </LinearLayout>  </LinearLayout>                  

That Layout contains the following components:

  1. LinearLayout – To society our elements linearly either vertically or horizontally.
  2. TextView – To render text
  3. ImageView – To render images.
  4. Push button – To allow us choose/select an image or capture one from the camera.

Classes

We take only one form.

(a). MainActivity.kt

Star by adding imports:

          import android.note.TargetApi import android.app.Activity import android.content.ContentUris import android.content.Intent import android.content.pm.PackageManager import android.graphics.BitmapFactory import android.net.Uri  import android.os.Build import android.os.Package import android.provider.DocumentsContract import android.provider.MediaStore import android.widget.Push import android.widget.ImageView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import androidx.core.content.FileProvider import java.io.File        

Then make our class extend the AppCompatActivity:

          form MainActivity : AppCompatActivity() {                  

Within the grade lets define our instance fields:

                      //Our variables     individual var mImageView: ImageView? = null     private var mUri: Uri? = nada     //Our widgets     individual lateinit var btnCapture: Button     private lateinit var btnChoose : Button     //Our constants     individual val OPERATION_CAPTURE_PHOTO = 1     individual val OPERATION_CHOOSE_PHOTO = 2        

In the above, the imageview will render our epitome, the Uri is the uri of the image. btnCapture will allow us start our photographic camera to capture the image. btnChoose volition allow us open the gallery to choose epitome.

Let's then create a method to initialize the above widgets:

                      private fun initializeWidgets() {         btnCapture = findViewById(R.id.btnCapture)         btnChoose = findViewById(R.id.btnChoose)         mImageView = findViewById(R.id.mImageView)     }                  

Then a method to bear witness our Toast message:

                      private fun show(message: String) {         Toast.makeText(this,message,Toast.LENGTH_SHORT).show()     }        

Adjacent nosotros will create a method to capture our photo or image:

                      private fun capturePhoto(){         val capturedImage = File(externalCacheDir, "My_Captured_Photo.jpg")         if(capturedImage.exists()) {             capturedImage.delete()         }         capturedImage.createNewFile()         mUri = if(Build.VERSION.SDK_INT >= 24){             FileProvider.getUriForFile(this, "info.camposha.kimagepicker.fileprovider",              capturedImage)         } else {             Uri.fromFile(capturedImage)         }          val intent = Intent("android.media.action.IMAGE_CAPTURE")         intent.putExtra(MediaStore.EXTRA_OUTPUT, mUri)         startActivityForResult(intent, OPERATION_CAPTURE_PHOTO)     }        

In the above method yous can see nosotros have started by instantiating a File we are calling capturedImage. We accept passed the location as well as the file name.

Then using the exists() method we have checked if a file with proper noun as the captured image does exist. If and then we delete.

Then nosotros create a new file using the createNewFile() method. The we obtain the Uri for the file. Take notation that if we are using a build sdk version of Android API Version 24 and in a higher place we use the FileProvider class, invoking its getUriForFile() method. Otherwise we utilise the good old fromFile() method of the Uri form.

And so nosotros instantiate our intent and startActivityForResult.

And so to open our gallery and filter images:

                      private fun openGallery(){         val intent = Intent("android.intent.action.GET_CONTENT")         intent.type = "image/*"         startActivityForResult(intent, OPERATION_CHOOSE_PHOTO)     }        

We will be rendering our image equally a bitmap:

                      private fun renderImage(imagePath: String?){         if (imagePath != nix) {             val bitmap = BitmapFactory.decodeFile(imagePath)             mImageView?.setImageBitmap(bitmap)         }         else {             evidence("ImagePath is nothing")         }     }                  

To obtain our image path nosotros volition use this method:

                      private fun getImagePath(uri: Uri?, selection: String?): String {         var path: Cord? = null         val cursor = contentResolver.query(uri, nix, option, null, naught )         if (cursor != cipher){             if (cursor.moveToFirst()) {                 path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.Data))             }             cursor.close()         }         return path!!     }        

Here is how we will handle our image on Android API Level 19 and to a higher place:

                      @TargetApi(19)     private fun handleImageOnKitkat(data: Intent?) {         var imagePath: String? = null         val uri = data!!.data         //DocumentsContract defines the contract between a documents provider and the platform.         if (DocumentsContract.isDocumentUri(this, uri)){             val docId = DocumentsContract.getDocumentId(uri)             if ("com.android.providers.media.documents" == uri.say-so){                 val id = docId.split(":")[1]                 val selsetion = MediaStore.Images.Media._ID + "=" + id                 imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,                  selsetion)             }             else if ("com.android.providers.downloads.documents" == uri.authority){                 val contentUri = ContentUris.withAppendedId(Uri.parse(                     "content://downloads/public_downloads"), java.lang.Long.valueOf(docId))                 imagePath = getImagePath(contentUri, zero)             }         }         else if ("content".equals(uri.scheme, ignoreCase = truthful)){             imagePath = getImagePath(uri, aught)         }         else if ("file".equals(uri.scheme, ignoreCase = true)){             imagePath = uri.path         }         renderImage(imagePath)     }                  

Total Code

Here is the total lawmaking for MainActivity.kt:

          package info.camposha.kimagepicker  import android.annotation.TargetApi import android.app.Activity import android.content.ContentUris import android.content.Intent import android.content.pm.PackageManager import android.graphics.BitmapFactory import android.internet.Uri  import android.bone.Build import android.os.Bundle import android.provider.DocumentsContract import android.provider.MediaStore import android.widget.Button import android.widget.ImageView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import androidx.cadre.content.FileProvider import java.io.File  grade MainActivity : AppCompatActivity() {     //Our variables     private var mImageView: ImageView? = null     private var mUri: Uri? = null     //Our widgets     private lateinit var btnCapture: Push     private lateinit var btnChoose : Push     //Our constants     private val OPERATION_CAPTURE_PHOTO = one     private val OPERATION_CHOOSE_PHOTO = ii      private fun initializeWidgets() {         btnCapture = findViewById(R.id.btnCapture)         btnChoose = findViewById(R.id.btnChoose)         mImageView = findViewById(R.id.mImageView)     }      private fun testify(bulletin: Cord) {         Toast.makeText(this,bulletin,Toast.LENGTH_SHORT).show()     }     private fun capturePhoto(){         val capturedImage = File(externalCacheDir, "My_Captured_Photo.jpg")         if(capturedImage.exists()) {             capturedImage.delete()         }         capturedImage.createNewFile()         mUri = if(Build.VERSION.SDK_INT >= 24){             FileProvider.getUriForFile(this, "info.camposha.kimagepicker.fileprovider",              capturedImage)         } else {             Uri.fromFile(capturedImage)         }          val intent = Intent("android.media.action.IMAGE_CAPTURE")         intent.putExtra(MediaStore.EXTRA_OUTPUT, mUri)         startActivityForResult(intent, OPERATION_CAPTURE_PHOTO)     }     individual fun openGallery(){         val intent = Intent("android.intent.action.GET_CONTENT")         intent.type = "paradigm/*"         startActivityForResult(intent, OPERATION_CHOOSE_PHOTO)     }     individual fun renderImage(imagePath: String?){         if (imagePath != null) {             val bitmap = BitmapFactory.decodeFile(imagePath)             mImageView?.setImageBitmap(bitmap)         }         else {             show("ImagePath is null")         }     }     private fun getImagePath(uri: Uri?, pick: Cord?): String {         var path: String? = nothing         val cursor = contentResolver.query(uri, goose egg, pick, null, null )         if (cursor != null){             if (cursor.moveToFirst()) {                 path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.Data))             }             cursor.close()         }         return path!!     }     @TargetApi(19)     individual fun handleImageOnKitkat(data: Intent?) {         var imagePath: Cord? = null         val uri = data!!.information         //DocumentsContract defines the contract between a documents provider and the platform.         if (DocumentsContract.isDocumentUri(this, uri)){             val docId = DocumentsContract.getDocumentId(uri)             if ("com.android.providers.media.documents" == uri.authorization){                 val id = docId.carve up(":")[one]                 val selsetion = MediaStore.Images.Media._ID + "=" + id                 imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,                  selsetion)             }             else if ("com.android.providers.downloads.documents" == uri.dominance){                 val contentUri = ContentUris.withAppendedId(Uri.parse(                     "content://downloads/public_downloads"), java.lang.Long.valueOf(docId))                 imagePath = getImagePath(contentUri, null)             }         }         else if ("content".equals(uri.scheme, ignoreCase = truthful)){             imagePath = getImagePath(uri, cipher)         }         else if ("file".equals(uri.scheme, ignoreCase = true)){             imagePath = uri.path         }         renderImage(imagePath)     }      override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out Cord>     , grantedResults: IntArray) {         super.onRequestPermissionsResult(requestCode, permissions, grantedResults)         when(requestCode){             1 ->                 if (grantedResults.isNotEmpty() && grantedResults.get(0) ==                  PackageManager.PERMISSION_GRANTED){                     openGallery()                 }else {                     show("Unfortunately Yous are Denied Permission to Perform this Operataion.")                 }         }     }      override fun onActivityResult(requestCode: Int, resultCode: Int, information: Intent?) {         super.onActivityResult(requestCode, resultCode, data)         when(requestCode){             OPERATION_CAPTURE_PHOTO ->                 if (resultCode == Activity.RESULT_OK) {                     val bitmap = BitmapFactory.decodeStream(                         getContentResolver().openInputStream(mUri))                     mImageView!!.setImageBitmap(bitmap)                 }             OPERATION_CHOOSE_PHOTO ->                 if (resultCode == Activity.RESULT_OK) {                     if (Build.VERSION.SDK_INT >= nineteen) {                         handleImageOnKitkat(data)                     }                 }         }     }      override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         setContentView(R.layout.activity_main)          initializeWidgets()          btnCapture.setOnClickListener{capturePhoto()}         btnChoose.setOnClickListener{             //bank check permission at runtime             val checkSelfPermission = ContextCompat.checkSelfPermission(this,              android.Manifest.permission.WRITE_EXTERNAL_STORAGE)             if (checkSelfPermission != PackageManager.PERMISSION_GRANTED){                 //Requests permissions to exist granted to this application at runtime                 ActivityCompat.requestPermissions(this,                  arrayOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE), ane)             }             else{                 openGallery()             }         }     } } //end                  

Resources

Here are downlaod and reference resources:

No. Site Link
ane. Github Scan
2. Github Download
iii. YouTube Sentry

Now motion to the adjacent tutorial.

Case 2: Android Select Image From Gallery and Show in ImageView

This 2d case is super uncomplicated and is written in java. Yous just click a button and via Intent we open up the Gallery. You cull the image y'all want and we render information technology direct on an ImageView.

Cheque the Gallery demo below:

How to Select Image From Gallery and Show it in ImageView Android

Let'southward start.

Step 1: Create Project

First by creating an empty Android Studio project.

Step ii: Dependencies

No third party or special dependency is needed for this project.

Footstep 3: Design Layout

Simply place a button in your layout. When that button is clicked we will open the gallery. Also add together an imageview that will render our selected image:

activity_main.xml

          <?xml version="one.0" encoding="utf-eight"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:paddingBottom="@dimen/activity_vertical_margin"     android:paddingLeft="@dimen/activity_horizontal_margin"     android:paddingRight="@dimen/activity_horizontal_margin"     android:paddingTop="@dimen/activity_vertical_margin">      <Button         android:id="@+id/upload_btn"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:text="Upload" />      <ImageView         android:id="@+id/paradigm"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_centerInParent="truthful"/> </RelativeLayout>                  

Step iv: Write Code

Hither is how nosotros open the Gallery for selecting images via Intent:

                      Intent intent = new Intent();                 intent.setType("paradigm/*");                 intent.setAction(Intent.ACTION_GET_CONTENT);                 startActivityForResult(Intent.createChooser(intent, "Select Motion-picture show"), SELECT_PICTURE);        

Hither is how nosotros get the real path of an paradigm provided we have it's Uri:

                      public Cord getPathFromURI(Uri contentUri) {         String res = cipher;         String[] proj = {MediaStore.Images.Media.DATA};         Cursor cursor = getContentResolver().query(contentUri, proj, nada, naught, null);         if (cursor.moveToFirst()) {             int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.Data);             res = cursor.getString(column_index);         }         cursor.shut();         return res;     }        

So here is how we render the selected epitome on an imageview:

                      public void onActivityResult(int requestCode, int resultCode, Intent data) {         if (resultCode == RESULT_OK) {             if (requestCode == SELECT_PICTURE) {                 // Get the url from data                 Uri selectedImageUri = data.getData();                 if (null != selectedImageUri) {                     // Get the path from the Uri                     Cord path = getPathFromURI(selectedImageUri);                     Log.i("MainActivity", "Image Path : " + path);                     // Set the image in ImageView                     image.setImageURI(selectedImageUri);                 }             }         }     }        

Here is the full code:

MainActivity.java

          public grade MainActivity extends AppCompatActivity {      private static final int SELECT_PICTURE = 100;     ImageView image;     Button upload_btn;     @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);         upload_btn= (Push button)findViewById(R.id.upload_btn);         prototype= (ImageView)findViewById(R.id.image);         upload_btn.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View 5) {                 Intent intent = new Intent();                 intent.setType("image/*");                 intent.setAction(Intent.ACTION_GET_CONTENT);                 startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);             }         });     }      public void onActivityResult(int requestCode, int resultCode, Intent data) {         if (resultCode == RESULT_OK) {             if (requestCode == SELECT_PICTURE) {                 // Get the url from data                 Uri selectedImageUri = information.getData();                 if (null != selectedImageUri) {                     // Go the path from the Uri                     String path = getPathFromURI(selectedImageUri);                     Log.i("MainActivity", "Image Path : " + path);                     // Set the epitome in ImageView                     prototype.setImageURI(selectedImageUri);                 }             }         }     }      /* Get the real path from the URI */     public Cord getPathFromURI(Uri contentUri) {         Cord res = nix;         String[] proj = {MediaStore.Images.Media.Data};         Cursor cursor = getContentResolver().query(contentUri, proj, nada, goose egg, null);         if (cursor.moveToFirst()) {             int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);             res = cursor.getString(column_index);         }         cursor.shut();         render res;     }                  

Run

Copy the code or download it in the link below, build and run.

Reference

Here are the reference links:

Number Link
ane. Download Example
two. Follow code author

Ezoic

Source: https://camposha.info/android-examples/android-capture-pick-image/

Posted by: swisherequat1983.blogspot.com

0 Response to "How To Capture Camera Image In Kotlin"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel