Building Cloud Expertise with centron - Our Tutorials

Whether you are a beginner or an experienced professional, our practical tutorials provide you with the knowledge you need to make the most of our cloud services.

Android Development: Making Image Capture Easy

Dive into the world of Android development with our latest blog post! Learn how to effortlessly integrate and display images from both the camera and gallery into your app. From permission management to displaying images in various views, our guide takes you through the process step by step. Dive in and explore the possibilities of image capture in Android!

Introduction

In today’s tutorial, we’ll develop an application that selects an image from either the camera or the gallery and displays it in an ImageView. Note: The code below works flawlessly for versions before Android Nougat.

Permissions

With the advent of Android Marshmallow, permissions need to be implemented at runtime. Add the following permissions to the AndroidManifest.xml file above the application tag.

<uses-feature android:name="android.hardware.camera" android:required="false" />
<uses-feature android:name="android.hardware.camera.autofocus" android:required="false" />
<uses-feature android:name="android.hardware.camera.flash" android:required="false" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

By adding android.hardware.camera, the Play Store recognizes and prevents the installation of the application on devices without a camera. Intent is the standard way to delegate actions to another application. To launch the native camera, the Intent requires android.provider.MediaStore.ACTION_IMAGE_CAPTURE. To select an image from the gallery, the Intent requires the following argument: Intent.ACTION_GET_CONTENT. In this tutorial, we invoke an image selector that allows us to choose an image from the camera or gallery and display it in a circular ImageView and a normal ImageView. Add the following dependency in the build.gradle file:

compile 'de.hdodenhof:circleimageview:2.1.0'

Project Structure for Android Image Capture

The layout for the activity_main.xml stays the same, except for the icon change for the FAB button to @android:drawable/ic_menu_camera. The content_main.xml content is as follows:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:id="@+id/content_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000000"
    android:padding="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".MainActivity"
    tools:showIn="@layout/activity_main">

    <RelativeLayout
        android:layout_width="250dp"
        android:layout_height="250dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:background="@drawable/image_border">

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:adjustViewBounds="true"
            android:scaleType="centerCrop" />
    </RelativeLayout>

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/img_profile"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_gravity="center_horizontal"
        android:src="@drawable/profile"
        app:civ_border_width="5dp"
        app:civ_border_color="#FFFFFF"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

MainActivity.java

The code for MainActivity.java is as follows:

public class MainActivity extends AppCompatActivity {

    Bitmap myBitmap;
    Uri picUri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(view -> startActivityForResult(getPickImageChooserIntent(), 200));
    }

    private Intent getPickImageChooserIntent() {
        Uri outputFileUri = getCaptureImageOutputUri();
        List<Intent> allIntents = new ArrayList<>();
        PackageManager packageManager = getPackageManager();

        Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
        for (ResolveInfo res : listCam) {
            Intent intent = new Intent(captureIntent);
            intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
            if (outputFileUri != null) {
                intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
            }
            allIntents.add(intent);
        }

        Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
        galleryIntent.setType("image/*");
        List<ResolveInfo> listGallery = packageManager.queryIntentActivities(galleryIntent, 0);
        for (ResolveInfo res : listGallery) {
            Intent intent = new Intent(galleryIntent);
            intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
            allIntents.add(intent);
        }

        Intent mainIntent = allIntents.get(allIntents.size() - 1);
        for (Intent intent : allIntents) {
            if (intent.getComponent().getClassName().equals("com.android.documentsui.DocumentsActivity")) {
                mainIntent = intent;
                break;
            }
        }
        allIntents.remove(mainIntent);

        Intent chooserIntent = Intent.createChooser(mainIntent, "Select source");
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, allIntents.toArray(new Parcelable[0]));

        return chooserIntent;
    }

    private Uri getCaptureImageOutputUri() {
        File getImage = getExternalCacheDir();
        return getImage != null ? Uri.fromFile(new File(getImage.getPath(), "profile.png")) : null;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            ImageView imageView = findViewById(R.id.imageView);
            CircleImageView croppedImageView = findViewById(R.id.img_profile);

            if (getPickImageResultUri(data) != null) {
                picUri = getPickImageResultUri(data);
                try {
                    myBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), picUri);
                    croppedImageView.setImageBitmap(myBitmap);
                    imageView.setImageBitmap(myBitmap);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private Uri getPickImageResultUri(Intent data) {
        return data != null && data.getAction() != null && data.getAction().equals(MediaStore.ACTION_IMAGE_CAPTURE)
                ? getCaptureImageOutputUri() : data.getData();
    }
}

Try Our Cloud Services for Effortless Android Development!

Are you looking to simplify your Android development process? With our cloud services, you can seamlessly integrate and display images from both the camera and gallery in your app. Sign up for a free trial today and experience the ease of managing permissions, invoking intents, and handling image capture directly from our robust and scalable cloud platform. Elevate your Android projects with our cutting-edge cloud solutions. Get started now!

Try for free!