How To Add The Auto Capture To Camera In Android Studio
Exercise you lot want to capture an image from the photographic camera and set it into imageview or upload it to the server? then, this is the right mail service to learn.
The camera is a very common characteristic that lots of apps provide. Most of the required image capture characteristic in own application. eg. profile image, creating a post with an paradigm, every food or social media app required camera feature in own application.
Basically, Paradigm capturing is a very elementary task, fifty-fifty if you lot are using custom. In this article, we are going to see how to capture images from the camera using FileProvider in your Android app.
Google introduces FileProvider in version 22.1.0. FileProvider course is a derived class from ContentProvider. In other words you lot tin can say, FileProvider provide facilitates to secure file sharing in android via content://Uri instead of a file:///Uri
checkout my other useful postal service:
How To Get Current Latitude And Longitude In Android
Google Places Autocomplete Android Case
Unmarried Sign-on with AppAuth Android [Step by Step]
So, Allow'south commencement with how can we attain capturing an image from the photographic camera and getting the file path, and load an image in an ImageView.
Step to capture image from camera programmatically
- Defining a FileProvider
- Granting Permissions to a URI, Storage & Camera
- Paradigm Capture using Photographic camera
- Manage Consequence and evidence image over the ImageView
1. Defining A FileProvider
Define a list of file paths for FileProvider in XML fileand salvage it in res/xml folder. Since we want to save merely in the public picture directory, we'll just add the path of it to XML.
<?xml version="1.0" encoding="utf-8"?> <paths xmlns:android="http://schemas.android.com/apk/res/android"> <external-path name="my_images" path="Android/data/com.case.captureimage/files/Pictures" /> </paths>
InAndroidMenifest.xml you have to specify the FileProvider component by adding an element<provider>similar below,
<provider android:name="androidx.core.content.FileProvider" android:authorities="com.instance.captureimage.fileprovider" android:exported="fake" android:grantUriPermissions="truthful"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths"></meta-data> </provider>
Note— Replacecom.example.captureimage with your package name
2. Granting Permissions To A URI, Storage & Camera
you demand to add the permission in the manifest file as,
<uses-feature android:proper name="android.hardware.photographic camera" android:required="truthful" />
In the permission, theandroid:required="true" is to tell Google's play to filter all the Android devices which accept a photographic camera function.
If we employandroid:required="faux", we need to cheque for the camera via programmatically.
<uses-permission android:proper name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.CAMERA" /> <uses-characteristic android:name="android.hardware.camera.autofocus" />
Android 6, contains a permission organisation for certain tasks. Each application can request the required permission on runtime. And then let'southward open the Activity class add the below code for requesting runtime permission,
if (ContextCompat.checkSelfPermission( this, Manifest.permission.Camera ) != PackageManager.PERMISSION_GRANTED ) { ActivityCompat.requestPermissions( this, arrayOf(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE), 0 ) } else { // Your code } } grab (ex: Exception) { // Error occurred while creating the File displayMessage(baseContext, ex.message.toString()) } } else { displayMessage(baseContext, "Zilch") } }
3. Epitome Capture Using Photographic camera
Now let's create a function to generate a random file proper noun with .jpg extension in the external files directory.
We need to create an Image file
@Throws(IOException::course) private fun createImageFile(): File { // Create an paradigm file name val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date()) val imageFileName = "JPEG_" + timeStamp + "_" val storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES) val prototype = File.createTempFile( imageFileName, /* prefix */ ".jpg", /* suffix */ storageDir /* directory */ ) // Save a file: path for use with ACTION_VIEW intents mCurrentPhotoPath = image.absolutePath return epitome }
Create a new Intent with FileProvider URI
try { photoFile = createImageFile() // Go on only if the File was successfully created if (photoFile != nada) { val photoURI = FileProvider.getUriForFile( this, "com.instance.captureimage.fileprovider", photoFile!! ) takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI) startActivityForResult(takePictureIntent, CAPTURE_IMAGE_REQUEST) } } catch (ex: Exception) { // Mistake occurred while creating the File displayMessage(baseContext, ex.message.toString()) }
4. Manage Result And Testify Image Over The ImageView
Later on action performing, nosotros will manage the result on onActivityResult by usingResultCode andRequestCode. InonActivityResult, we take to manage three things.
- Get actual file path or file from result intent
- Compress a file using the FileCompressor utility
- Finally fix terminal output over the ImageView in Android
override fun onActivityResult(requestCode: Int, resultCode: Int, information: Intent?) { super.onActivityResult(requestCode, resultCode, information) if (requestCode == CAPTURE_IMAGE_REQUEST && resultCode == Activeness.RESULT_OK) { val myBitmap = BitmapFactory.decodeFile(photoFile!!.absolutePath) imageView.setImageBitmap(myBitmap) } else { displayMessage(baseContext, "Request cancelled or something went wrong.") } }
Final MainActivity.kt
class MainActivity : AppCompatActivity() { var photoFile: File? = zero val CAPTURE_IMAGE_REQUEST = i var mCurrentPhotoPath: String? = nada override fun onCreate(savedInstanceState: Packet?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) button_capture.setOnClickListener { captureImage() } } private fun captureImage() { if (ContextCompat.checkSelfPermission( this, Manifest.permission.CAMERA ) != PackageManager.PERMISSION_GRANTED ) { ActivityCompat.requestPermissions( this, arrayOf(Manifest.permission.Camera, Manifest.permission.WRITE_EXTERNAL_STORAGE), 0 ) } else { val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) if (takePictureIntent.resolveActivity(packageManager) != zip) { // Create the File where the photograph should go try { photoFile = createImageFile() // Go along only if the File was successfully created if (photoFile != null) { val photoURI = FileProvider.getUriForFile( this, "com.case.captureimage.fileprovider", photoFile!! ) takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI) startActivityForResult(takePictureIntent, CAPTURE_IMAGE_REQUEST) } } take hold of (ex: Exception) { // Error occurred while creating the File displayMessage(baseContext, ex.message.toString()) } } else { displayMessage(baseContext, "Zero") } } } @Throws(IOException::course) private fun createImageFile(): File { // Create an image file name val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss").format(Appointment()) val imageFileName = "JPEG_" + timeStamp + "_" val storageDir = getExternalFilesDir(Environs.DIRECTORY_PICTURES) val image = File.createTempFile( imageFileName, /* prefix */ ".jpg", /* suffix */ storageDir /* directory */ ) // Save a file: path for utilise with ACTION_VIEW intents mCurrentPhotoPath = prototype.absolutePath return paradigm } private fun displayMessage(context: Context, message: String) { Toast.makeText(context, message, Toast.LENGTH_LONG).bear witness() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == CAPTURE_IMAGE_REQUEST && resultCode == Activity.RESULT_OK) { val myBitmap = BitmapFactory.decodeFile(photoFile!!.absolutePath) imageView.setImageBitmap(myBitmap) } else { displayMessage(baseContext, "Request cancelled or something went wrong.") } } }
Download the example inGithub
Screenshot
Also, check out my other post on kotlin,
Implementing Pull To Refresh In Android
Popupwindow Android example in Kotlin
Android Image Slider With Indicator Case
Source: https://howtodoandroid.com/capture-image-android/
Posted by: pearsoncoight.blogspot.com
0 Response to "How To Add The Auto Capture To Camera In Android Studio"
Post a Comment