Android

Android Choosing an image from Camera or Gallery with Cropping functionality | Vishal Swami

Pinterest LinkedIn Tumblr

Here’s an example of an Android application that allows users to choose an image from the camera or gallery and perform cropping functionality using the “Android Image Cropper” library.

Step 1: Set up the project

Start by creating a new Android project in Android Studio. Make sure you have the necessary dependencies and permissions in your project’s build.gradle file:

dependencies {
    implementation 'com.theartofdev.edmodo:android-image-cropper:2.8.+'
}

Also, make sure you have the necessary permissions in your AndroidManifest.xml file:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />

Step 2: Create the layout

Create a layout file called activity_main.xml with the following code:

<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:paddingLeft="16dp"
    android:paddingTop="16dp"
    android:paddingRight="16dp"
    android:paddingBottom="16dp"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:scaleType="centerInside"
        android:src="@drawable/placeholder" />

    <Button
        android:id="@+id/btnChooseImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/imageView"
        android:text="Choose Image" />

    <Button
        android:id="@+id/btnCropImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/btnChooseImage"
        android:text="Crop Image"
        android:enabled="false" />

</RelativeLayout>

Step 3: Implement the functionality in the MainActivity

Open MainActivity.java and add the following code:

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_CAMERA_PERMISSION = 200;
    private static final int REQUEST_IMAGE_CAPTURE = 100;
    private static final int REQUEST_IMAGE_GALLERY = 101;

    private ImageView imageView;
    private Button btnChooseImage;
    private Button btnCropImage;

    private Uri imageUri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imageView = findViewById(R.id.imageView);
        btnChooseImage = findViewById(R.id.btnChooseImage);
        btnCropImage = findViewById(R.id.btnCropImage);

        btnChooseImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chooseImage();
            }
        });

        btnCropImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cropImage(imageUri);
            }
        });
    }

    private void chooseImage() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
        } else {
            openImageChooser();
        }
    }

    private void openImageChooser() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        startActivityForResult(intent, REQUEST_IMAGE_GALLERY);
    }

    private void cropImage(Uri imageUri) {
        CropImage.activity(imageUri)
                .setGuidelines(CropImageView.Guidelines.ON)
                .setAspectRatio(1, 1)
                .start(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            cropImage(imageUri);
        } else if (requestCode == REQUEST_IMAGE_GALLERY && resultCode == RESULT_OK && data != null) {
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), data.getData());
                imageView.setImageBitmap(bitmap);
                imageUri = data.getData();
                btnCropImage.setEnabled(true);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
            CropImage.ActivityResult result = CropImage.getActivityResult(data);
            if (resultCode == RESULT_OK) {
                Uri resultUri = result.getUri();
                try {
                    Bitmap croppedBitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), resultUri);
                    imageView.setImageBitmap(croppedBitmap);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
                Exception error = result.getError();
                error.printStackTrace();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CAMERA_PERMISSION && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            openImageChooser();
        }
    }
}

That’s it! Now you have an Android application that allows users to choose an image from the camera or gallery and perform cropping functionality. Remember to replace the placeholder image with an actual placeholder image of your choice.

Note: Don’t forget to add the necessary runtime permissions check in your code to handle permissions for accessing the camera and gallery.

Vishal Swami is a hardcore Android programmer and Android programming has been his passion since he compiled his first hello-world program. Solving real problems of Android developers through tutorials has always been an interesting part for him.

57 Comments

  1. I am often to blogging and i really appreciate your content. The article has really peaks my interest. I am going to bookmark your site and keep checking for new information.

  2. شرکت ایمن زاهدان با ارتقاء سطح امنیت و خدمات حفاظ و درب فرفورژه به عنوان یک نخبه در زمینه امنیت معرفی می شود. این شرکت با ارائه خدمات نصب و تعمیر حفاظات دیواری، حفاظ شکاری، حفاظ پنجره، پنجره دوجداره، درب آکاردئونی، درب آهنی ویلایی، کرکره برقی، جک پارکینگی، درب اتوماتیک شیشه ای، راهبندها و دزدگیر مکان ها، به مشتریان خود امنیت بی نظیری ارائه می دهد. https://imenzahedan.ir/

  3. you’re really a good webmaster. The site loading speed is amazing. It seems that you’re doing any unique trick. Also, The contents are masterpiece. you’ve done a great job on this topic!

  4. Hello There. I found your blog using msn. This is an extremely well written article. I’ll make sure to bookmark it and come back to read more of your useful info. Thanks for the post. I’ll certainly return.

  5. What i do not realize is actually how you’re not really much more well-liked than you may be right now. You are very intelligent. You realize therefore significantly relating to this subject, made me personally consider it from a lot of varied angles. Its like women and men aren’t fascinated unless it is one thing to accomplish with Lady gaga! Your own stuffs great. Always maintain it up!

  6. I feel that is among the most vital info for me. And i’m happy studying your article. But want to remark on few normal things, The site taste is wonderful, the articles is in point of fact great : D. Excellent task, cheers

  7. Thank you so much for giving everyone an extremely splendid chance to read in detail from this website. It is often so great and also packed with amusement for me and my office colleagues to visit the blog a minimum of 3 times weekly to study the latest things you have. Of course, I am also certainly satisfied with your spectacular creative concepts you serve. Some two ideas in this article are definitely the finest we have all ever had.

  8. Hi, just required you to know I he added your site to my Google bookmarks due to your layout. But seriously, I believe your internet site has 1 in the freshest theme I??ve came across. It extremely helps make reading your blog significantly easier.

  9. Wow! Thank you! I permanently needed to write on my website something like that. Can I include a part of your post to my blog?

  10. Valuable info. Lucky me I found your web site by accident, and I’m shocked why this accident didn’t happened earlier! I bookmarked it.

  11. I’m extremely impressed with your writing skills as well as with the layout on your blog. Is this a paid theme or did you customize it yourself? Anyway keep up the nice quality writing, it’s rare to see a nice blog like this one nowadays..

  12. Hi I am so glad I found your weblog, I really found you by error, while I was researching on Aol for something else, Regardless I am here now and would just like to say thank you for a tremendous post and a all round interesting blog (I also love the theme/design), I don’t have time to browse it all at the moment but I have bookmarked it and also included your RSS feeds, so when I have time I will be back to read much more, Please do keep up the superb work.

  13. I used to be suggested this blog through my cousin. I’m no longer positive whether this post is written through him as no one else understand such special about my problem. You’re incredible! Thank you!

  14. Hello! I just wanted to ask if you ever have any problems with hackers? My last blog (wordpress) was hacked and I ended up losing months of hard work due to no backup. Do you have any solutions to stop hackers?

  15. Hi , I do believe this is an excellent blog. I stumbled upon it on Yahoo , i will come back once again. Money and freedom is the best way to change, may you be rich and help other people.

  16. Hello there! This is kind of off topic but I need some guidance from an established blog. Is it hard to set up your own blog? I’m not very techincal but I can figure things out pretty quick. I’m thinking about making my own but I’m not sure where to start. Do you have any ideas or suggestions? Thank you

  17. Hello! I could have sworn I’ve been to this blog before but after browsing through some of the post I realized it’s new to me. Anyways, I’m definitely happy I found it and I’ll be book-marking and checking back frequently!

  18. Very good written information. It will be useful to everyone who utilizes it, as well as yours truly :). Keep doing what you are doing – for sure i will check out more posts.

  19. An impressive share, I just given this onto a colleague who was doing a little analysis on this. And he in fact bought me breakfast because I found it for him.. smile. So let me reword that: Thnx for the treat! But yeah Thnkx for spending the time to discuss this, I feel strongly about it and love reading more on this topic. If possible, as you become expertise, would you mind updating your blog with more details? It is highly helpful for me. Big thumb up for this blog post!

  20. Wow, superb blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your site is fantastic, as well as the content!

  21. You can certainly see your enthusiasm in the work you write. The world hopes for more passionate writers like you who are not afraid to say how they believe. Always go after your heart.

Write A Comment