Android Image Cropping Example Tutorial Pick Gallery Camera Image

How to select image from Android Gallery & Camera than crop and show into ImageView coding with runtime camera permission support Marshmallow feature.

Image cropping is one of the of the best feature of android mobile phone and mostly used where developer gives the facility to modify and resize any image by its users. So in this tutorial we are going to perform some certain functionality like user can select image from both camera and gallery then after selection it will open directly image inside image cropping window, where its user can modify or Resize image size by itself . After done everything all you have to do it click on OK button and it will show the cropped image inside ImageView. So here is the complete step by step tutorial for Android Image Cropping Example Tutorial Pick Gallery Camera Image .

android-project-download-code-button

Android Image Cropping Example Tutorial Pick Gallery Camera Image.

Add all below three permissions inside AndroidManifest.xml file.

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.camera" />

Code for MainActivity.java file.

package com.android_examples.cropimage_android_examplescom;
import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;

public class MainActivity extends AppCompatActivity {

    ImageView imageView;
    Button buttonCamera, buttonGallery ;
    File file;
    Uri uri;
    Intent CamIntent, GalIntent, CropIntent ;
    public  static final int RequestPermissionCode  = 1 ;
    DisplayMetrics displayMetrics ;
    int width, height;

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

        imageView = (ImageView)findViewById(R.id.imageview);
        buttonCamera = (Button)findViewById(R.id.button2);
        buttonGallery = (Button)findViewById(R.id.button1);

        EnableRuntimePermission();

        buttonCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                ClickImageFromCamera() ;

            }
        });

        buttonGallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                GetImageFromGallery();

            }
        });

    }

    public void ClickImageFromCamera() {

        CamIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

        file = new File(Environment.getExternalStorageDirectory(),
         "file" + String.valueOf(System.currentTimeMillis()) + ".jpg");
        uri = Uri.fromFile(file);

        CamIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, uri);

        CamIntent.putExtra("return-data", true);

        startActivityForResult(CamIntent, 0);

    }

    public void GetImageFromGallery(){

        GalIntent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

        startActivityForResult(Intent.createChooser(GalIntent, "Select Image From Gallery"), 2);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0 && resultCode == RESULT_OK) {

            ImageCropFunction();

        }
        else if (requestCode == 2) {

            if (data != null) {

                uri = data.getData();

                ImageCropFunction();

            }
        }
        else if (requestCode == 1) {

            if (data != null) {

                Bundle bundle = data.getExtras();

                Bitmap bitmap = bundle.getParcelable("data");

                imageView.setImageBitmap(bitmap);

            }
        }
    }

    public void ImageCropFunction() {

        // Image Crop Code
        try {
            CropIntent = new Intent("com.android.camera.action.CROP");

            CropIntent.setDataAndType(uri, "image/*");

            CropIntent.putExtra("crop", "true");
            CropIntent.putExtra("outputX", 180);
            CropIntent.putExtra("outputY", 180);
            CropIntent.putExtra("aspectX", 3);
            CropIntent.putExtra("aspectY", 4);
            CropIntent.putExtra("scaleUpIfNeeded", true);
            CropIntent.putExtra("return-data", true);

            startActivityForResult(CropIntent, 1);

        } catch (ActivityNotFoundException e) {

        }
    }
        //Image Crop Code End Here

    public void EnableRuntimePermission(){

        if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                Manifest.permission.CAMERA))
        {

            Toast.makeText(MainActivity.this,"CAMERA permission allows us to Access CAMERA app", Toast.LENGTH_LONG).show();

        } else {

            ActivityCompat.requestPermissions(MainActivity.this,new String[]{
                    Manifest.permission.CAMERA}, RequestPermissionCode);

        }
    }

    @Override
    public void onRequestPermissionsResult(int RC, String per[], int[] PResult) {

        switch (RC) {

            case RequestPermissionCode:

                if (PResult.length > 0 && PResult[0] == PackageManager.PERMISSION_GRANTED) {

                    Toast.makeText(MainActivity.this,"Permission Granted, Now your application can access CAMERA.", Toast.LENGTH_LONG).show();

                } else {

                    Toast.makeText(MainActivity.this,"Permission Canceled, Now your application cannot access CAMERA.", Toast.LENGTH_LONG).show();

                }
                break;
        }
    }

}

Code for activity_main.xml layout file.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    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"
    android:background="#FFECB3"
    tools:context="com.android_examples.cropimage_android_examplescom.MainActivity">

    <ImageView
        android:layout_width="250dp"
        android:layout_height="325dp"
        android:id="@+id/imageview"
        android:layout_centerHorizontal="true"
        />

    <Button
        android:text="Click Here For PICK image from Gallery TO CROP"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/imageview"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="7dp"
        android:id="@+id/button1" />

    <Button
        android:text="Click Here For CLICK image from Camera TO CROP"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button1"
        android:layout_alignRight="@+id/button1"
        android:layout_alignEnd="@+id/button1"
        android:layout_marginTop="7dp"
        android:id="@+id/button2" />
</RelativeLayout>

Code for AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.android_examples.cropimage_android_examplescom">

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-feature android:name="android.hardware.camera" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Screenshots:

Click here to download Android Image Cropping Example Tutorial Pick Gallery Camera Image project with source code.

21 Comments

  1. Thank so much

  2. this is not working i n android 7

  3. sathish kumar p

    Any update about Android Nougat 7 Camera and Gallery Issue

  4. Hi ,

    for me the above code is giving error
    java.lang.SecurityException: Uid 10573 does not have permission to uri
    can you please help me

  5. Kaung Htet Aung

    I am on kit kat version. but taking photo is fine , and showing image in imageview is blur. What do i do?? please help me

    • Kaung image is blur because we have define the imageView size so the image forced to set inside it. But if you save this image in your device or upload this image on server then the image should be fine.

  6. Hello
    I work with AIDE. Image Cropping
    I enter and there is no problem
    But when the APP runs, it stops. . . please guide me
    Thankful

  7. Hello
    fixed
    I work with AIDE, it does not seem to support AppcompatActivity
    I used the activity and got it right
    Thank

  8. I used this code and it works …thanks a lot for this post

  9. Hi, thanks for the nice simple example. My croped pics are losing on quality after croping. Do you have an idea why and how I can keep the quality?

    Thanks!

  10. Above example not working on marshmallow os , on other os its working fine. Please update me…

  11. App Get crashed after cropping image in onActivityResult()

Leave a Reply

Your email address will not be published. Required fields are marked *