<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jahaber Shaik Allavudeen on Medium]]></title>
        <description><![CDATA[Stories by Jahaber Shaik Allavudeen on Medium]]></description>
        <link>https://medium.com/@blackzshaik?source=rss-5883a19ec878------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*UNrL1FBdJPWAdK3_V5jxlw.jpeg</url>
            <title>Stories by Jahaber Shaik Allavudeen on Medium</title>
            <link>https://medium.com/@blackzshaik?source=rss-5883a19ec878------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 10:57:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@blackzshaik/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Build an Android Photo Capturing App with Kotlin Using CameraX]]></title>
            <link>https://medium.com/@blackzshaik/build-an-android-photo-capturing-app-with-kotlin-using-camerax-98c27f3ff795?source=rss-5883a19ec878------2</link>
            <guid isPermaLink="false">https://medium.com/p/98c27f3ff795</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android-camera]]></category>
            <category><![CDATA[jetpack]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-developers]]></category>
            <dc:creator><![CDATA[Jahaber Shaik Allavudeen]]></dc:creator>
            <pubDate>Sat, 06 May 2023 18:31:55 GMT</pubDate>
            <atom:updated>2023-05-06T18:31:55.059Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello readers,</p><p>In this post, I’ll share how we are going to create a photo-capturing app using Kotlin and Android CameraX library</p><p>CameraX is a jetpack library built on top of Camera2 and it helps us achieve better results with less code. And we don’t have to worry about device-specific issues.</p><p>You can learn more about CameraX here: <a href="https://developer.android.com/training/camerax">https://developer.android.com/training/camerax</a></p><p>Let&#39;s get started, like every other jetpack library, we will start by adding dependencies</p><pre> def camerax_version = &quot;1.3.0-alpha06&quot;<br> implementation &quot;androidx.camera:camera-camera2:${camerax_version}&quot;<br> implementation &quot;androidx.camera:camera-lifecycle:${camerax_version}&quot;<br> implementation &quot;androidx.camera:camera-view:${camerax_version}&quot;</pre><p>Add the above dependencies to your app-level build.gradle.</p><p>Then the next thing we want to add is a preview so that we can display the output on the screen. For that, we will be using PreviewView</p><pre>&lt;androidx.camera.view.PreviewView<br>        android:id=&quot;@+id/previewView&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;match_parent&quot; /&gt;</pre><p>Add the PreviewView to your activity or fragment.</p><p>Initially, we want to show the input we get from the camera and display the output in our preview. To get the camera we will start by declaring a ListenableFuture since the execution of the camera will happen in the main thread.</p><pre>private lateinit var cameraProviderFuture: ListenableFuture&lt;ProcessCameraProvider&gt;<br>private lateinit var camera: Camera<br><br>//onCreate<br><br>cameraProviderFuture = ProcessCameraProvider.getInstance(this)<br><br>cameraProviderFuture.addListener({<br>            cameraProvider = cameraProviderFuture.get()<br>            bindPreview(cameraProvider, backCameraSelector)<br>        }, ContextCompat.getMainExecutor(this))</pre><p>After declaring the ListenableFuture we will get the singleton instance of the ProcessCameraProvider’s instance with the getInstance(context) function, on which we have added a listener with an Executor which will run the Runnable task in the main thread.</p><p>The listener will get called once the <em>Future </em>is completed, here the <em>Future </em>is our request to access the camera. Once we are good to go, we safely use the camera provider to show the preview.</p><pre>private fun bindPreview(cameraProvider: ProcessCameraProvider, cameraSelector: CameraSelector) {<br>       <br>     val preview = Preview.Builder().build()<br><br>     val previewView = findViewById&lt;PreviewView&gt;(R.id.previewView)<br><br>     preview.setSurfaceProvider(previewView.surfaceProvider)<br><br>     camera = cameraProvider.bindToLifecycle(<br>          this as LifecycleOwner,<br>          cameraSelector,<br>          preview<br>      )<br><br>    }</pre><p>Here is the bindPreview, this is our implementation to show the preview, at first we create the Preview object, then set the surface provider with the surface provider from the PreviewView from our layout. Then we need Camera Selector to define which camera to use. Once we have everything the next step is to call bindToLifecyle.</p><p>bindToLifecycle will take a lifecycle owner, so it can always be aware when the activity is visible to the user and not. A camera selector to determine which camera to use, whether front or back. And the final parameter is a use case, it is a vararg that can accept multiple use cases. In the CameraX architecture actions as considered as use cases, and these actions are Preview, Image Capture, Image Analysis, and Video Capture. As a first step, we only need the preview so we are only passing the preview use case.</p><p>Here is a small helper for Camera Selector for both the front and back camera</p><pre><br>private val backCameraSelector by lazy {<br>        getCameraSelector(CameraSelector.LENS_FACING_BACK)<br>    }<br><br>    private val frontCameraSelector by lazy {<br>        getCameraSelector(CameraSelector.LENS_FACING_FRONT)<br>    }<br><br>private fun getCameraSelector(lensFacing: Int) =<br>        CameraSelector.Builder().requireLensFacing(lensFacing).build()</pre><p>At this point, if you have all the code in your activity and run the app you might be able to see the camera preview, if not, don’t worry, post in the comments what issue you’re facing, I’ll help you with that.</p><p>And if you’re going to run the app, don’t forget to add the camera permission in the manifest</p><pre>&lt;uses-feature android:name=&quot;android.hardware.camera&quot; /&gt;</pre><p>And you can enable the permission directly from the app info page in the settings, do this only if you’re running a sample.</p><blockquote>Tip: Try with a real device first, then only run it on an emulator</blockquote><p>Now comes the interesting, some of you just scrolled to this section right :D</p><p>Taking pictures with the CameraX library, is really simple, as we mentioned earlier, actions like Image Capture are a Use Case in the CameraX architecture. As we did for Preview, we need to create an ImageCapture use case and bind it without the camera provider’s lifecycle.</p><pre>private lateinit var imageCapture: ImageCapture<br><br>imageCapture =<br>            ImageCapture.Builder().setTargetRotation(previewView.display.rotation).build()</pre><p>Declare an ImageCapture use case and create an object using the builder and bind it.</p><p>Now our bindPreview function will look like this,</p><pre>private fun bindPreview(cameraProvider: ProcessCameraProvider, cameraSelector: CameraSelector) {<br>        val preview = Preview.Builder().build()<br>        val previewView = findViewById&lt;PreviewView&gt;(R.id.previewView)<br><br>        preview.setSurfaceProvider(previewView.surfaceProvider)<br><br>        imageCapture =<br>            ImageCapture.Builder().setTargetRotation(previewView.display.rotation).build()<br><br>        camera = cameraProvider.bindToLifecycle(<br>            this as LifecycleOwner,<br>            cameraSelector,<br>            preview,<br>            imageCapture<br>        )<br><br>    }</pre><p>Then simply takePicture, pun intended.</p><p>We have to call the takePicture function in our ImageCapture use case to take pictures from the camera and save it to our local storage.</p><pre>imageCapture.takePicture(<br>            getImageOutputOptions(),<br>            ContextCompat.getMainExecutor(this),<br>            this<br>        )</pre><p>takePicture has three parameters, the first one is the ImageOutputOptions, which defines how and where the image should be saved, alternately you can simply pass a File. The second is the Executor, in which the task will run. And the last “this” is a callback, ImageCapture.OnImageSavedCallback will provide us with the details about the image-saving status.</p><p>Here are the ImageOutputOptions,</p><pre>private fun getImageOutputOptions(): ImageCapture.OutputFileOptions {<br>        val contentResolver = applicationContext.contentResolver<br>        val contentValues: ContentValues = ContentValues()<br>        contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, &quot;IMG_${System.currentTimeMillis()}&quot;)<br>        contentValues.put(MediaStore.MediaColumns.MIME_TYPE, &quot;image/jpeg&quot;)<br>        return ImageCapture.OutputFileOptions.Builder(<br>            contentResolver,<br>            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,<br>            contentValues<br>        ).build()<br>    }</pre><p>I ran the sample on an Android 11 device if you’re running on devices below Android 11, don’t forget to add permission and allow them from settings.</p><p>And the callbacks</p><pre>override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {<br>        Snackbar.make(<br>            findViewById(R.id.rootView),<br>            &quot;Image saved successfully&quot;,<br>            Snackbar.LENGTH_SHORT<br>        ).show()<br>    }<br><br>    override fun onError(exception: ImageCaptureException) {<br>        exception.printStackTrace()<br>    }</pre><p>Once the image is saved on the device the onImageSaved will get called, if there is an error, onError will be called.</p><p>Here is a story on what is going on above,</p><p>We are trying to build a Photo Capturing app, so the first thing we want is to show a preview, and to show the preview we need to get the preview from the camera, Unlike Camera2 and Camera APIs in Android, CameraX is a lifecycle-aware camera, because of which we will be using a ListenableFuture, And yes this word is confusing me as well (let me know you’re thoughts on the comments), but in a nutshell, it is just like a Task which runs on a main thread. And the task we are giving to the ListenableFuture is that ask it to provide access to the camera using ProcessCameraProvider, once it got access to the camera the listener added to the ListenableFuture will be called.</p><p>Now we have access to the Android device’s camera, we can get it from our ProcessCameraProvider object, Now that we have access to the camera, and we know that this camera is lifecycle-aware, we need to bind to a lifecycle, then we can achieve our goals on showing a preview and as well as taking a photo with it. And in the CameraX architecture these actions are called Use Cases, as the function name, we are binding the lifecycle in which the camera needs to run, which camera it needs to run (front/back ), and the use cases the camera can provide. And that&#39;s it, once your camera provider is bound, you can show the preview as well as take pictures of it.</p><p>This article is just the tip of an iceberg about CameraX, there is much more about it, I’ll try my best to explain everything in the upcoming articles.</p><p>Android Image Capturing App with Kotlin and CameraX complete source code GitHub Link:</p><p><a href="https://github.com/blackzshaik/CameraX-Sample-App">GitHub - blackzshaik/CameraX-Sample-App: Image capture App in Android created using CameraX library in Kotlin</a></p><p>PS: This is my first article here in Medium so…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98c27f3ff795" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>