Storing captured image or an image picked from a gallery in internal storage using file provider android.

Android Camera intent not working in android nougat and above. File provider used to capture an image and pick an image from the gallery.  Capture image from the camera and stored in the internal storage in android nougat and above.


It will show you how to use File Provider when you set your target SDK as 24 and change following.

1) Create file_path.xml


<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>



2) In AndroidMainfest inside application tag


//Here authoitties is unique identification of the fileprovider
<provider    android:name="android.support.v4.content.FileProvider"
    android:authorities="${applicationId}.fileProvider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>



3) In oncreate method.



try {
    if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.M) {
        fileUri = FileProvider.getUriForFile(MainActivity.this, BuildConfig.APPLICATION_ID+".fileProvider", createImageFile());
    } else {
        fileUri = Uri.fromFile(createImageFile());
    }
} catch (Exception d) {
    d.printStackTrace();
}




private File createImageFile() throws IOException {
    // Create an image file name    String imageFileName = "_your_profile_photo";
    File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    storageDir.mkdirs();

    //("prefix","suffix","storage")    image = File.createTempFile(imageFileName, ".jpg", storageDir);
    return image;
}



Full code of xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:gravity="center"
    android:id="@+id/container"
    android:orientation="vertical"
    tools:context="com.yang.demoprojects.MainActivity">

    <ImageView
        android:id="@+id/imageview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/take_photo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Take photo"/>
    <Button
        android:id="@+id/pick_from_galalery"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Pick from gallery"/>
</LinearLayout>




Full code for main activity

package com.yang.demoprojects;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    Button takephoto, pickfromGallery;
    ImageView imageView;
    File image;
    Uri fileUri;
    private static int CAMERA_PIC_REQUEST=0;
    private static int PICK_IMAGE_REQUEST=1;
    static final Integer WRITE_EXST = 0x3;
    static final Integer READ_EXST = 0x4;
    static final Integer CAMERA = 0x5;
    Bitmap bitmap=null;

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

    public void init() {
        takephoto = (Button) findViewById(R.id.take_photo);
        pickfromGallery = (Button) findViewById(R.id.pick_from_galalery);
        imageView=(ImageView)findViewById(R.id.imageview);
        takephoto.setOnClickListener(this);
        pickfromGallery.setOnClickListener(this);
        try {
            if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.M) {
                fileUri = FileProvider.getUriForFile(MainActivity.this, BuildConfig.APPLICATION_ID+".fileProvider", createImageFile());
            } else {
                fileUri = Uri.fromFile(createImageFile());
            }
        } catch (Exception d) {
            d.printStackTrace();
            Toast.makeText(this, " sandeep \n" + fileUri + "\n\n" + d.getMessage().toString(), Toast.LENGTH_LONG).show();
        }
    }

    @Override    public void onClick(View v) {

        if (v.getId() == R.id.take_photo) {
            //Upload from camera            try {
                handleMedia(true);
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else if (v.getId() == R.id.pick_from_galalery) {
            //Upload from Gallery            try {
                handleMedia(false);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    private File createImageFile() throws IOException {
        // Create an image file name        String imageFileName = "_your_profile_photo";
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        storageDir.mkdirs();

        //("prefix","suffix","storage")
        image = File.createTempFile(imageFileName, ".jpg", storageDir);
        return image;
    }

    private void handleMedia(boolean isCameraSelected) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            allPermission();
            if (isCameraSelected) {
                openCamera(fileUri);
            } else {
                openGallery();
            }
        } else {
            if (isCameraSelected)
                openCamera(fileUri);
            else                openGallery();
        }

    }

    private void openCamera(Uri fileUri) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        startActivityForResult(intent, MainActivity.CAMERA_PIC_REQUEST);
    }

    private void openGallery() {
        Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(i, MainActivity.PICK_IMAGE_REQUEST);
    }

    public void allPermission(){
        askForPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE,WRITE_EXST);
        askForPermission(Manifest.permission.READ_EXTERNAL_STORAGE,READ_EXST);
        askForPermission(Manifest.permission.CAMERA,CAMERA);
    }

    private void askForPermission(String permission, Integer requestCode) {
        if (ContextCompat.checkSelfPermission(MainActivity.this, permission) != PackageManager.PERMISSION_GRANTED) {

            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, permission)) {
                //This is called if user has denied the permission before
                //In this case I am just asking the permission again
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{permission}, requestCode);
            } else {

                ActivityCompat.requestPermissions(MainActivity.this, new String[]{permission}, requestCode);
            }
        } else {
            Toast.makeText(this, "" + permission + " is already granted.", Toast.LENGTH_SHORT).show();
        }
    }

    @Override    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(ActivityCompat.checkSelfPermission(this, permissions[0]) == PackageManager.PERMISSION_GRANTED){
            switch (requestCode) {
                //Write external Storage
                case 3:
                    break;
                //Read External Storage
                case 4:
                    Intent imageIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(imageIntent, 11);
                    break;
                //Camera
                case 5:
                    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                        startActivityForResult(takePictureIntent, 12);
                    }
                    break;
            }

            Toast.makeText(this, "Permission granted", Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
        }
    }

    @Override    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        try {

            if (requestCode == CAMERA_PIC_REQUEST && resultCode == Activity.RESULT_OK) {
                if (fileUri != null) {

                    BitmapFactory.Options opts = new BitmapFactory.Options();
                    opts.inSampleSize = 2;
                    bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(), opts);
                    displayImage(bitmap, image);
                }
            }

            else if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
                Uri selectedImageUri = data.getData();
                String selectedImagePath = getPath(selectedImageUri, MainActivity.this);
                bitmap = reduceImageSize(selectedImagePath);

                displayImage(bitmap, image);
            }
        }catch (Exception d){}
    }

    public void writeFilesfromCamera(Bitmap thumbnail, String path) {
        FileOutputStream out;

        try {

            out = new FileOutputStream(new File(path));

            Bitmap scaledBitmap = Bitmap.createScaledBitmap(thumbnail,
                    thumbnail.getWidth(), thumbnail.getHeight(), false);
            scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 75, out);
            scaledBitmap = RotateBitmap(bitmap, 90);
            imageView.setImageBitmap(scaledBitmap);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getPath(Uri uri, Activity act) {
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        if (cursor != null) {
            // HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL            // THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } else            return null;
    }

    public static Bitmap reduceImageSize(String mSelectedImagePath) {

        Bitmap m = null;
        try {
            File f = new File(mSelectedImagePath);

            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f), null, o);

            // The new size we want to scale to
            final int REQUIRED_SIZE = 150;

            // Find the correct scale value. It should be the power of 2.
            int width_tmp = o.outWidth, height_tmp = o.outHeight;
            int scale = 1;
            while (true) {
                if (width_tmp / 2 < REQUIRED_SIZE
                        || height_tmp / 2 < REQUIRED_SIZE)
                    break;
                width_tmp /= 2;
                height_tmp /= 2;
                scale *= 2;
            }

            // Decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            m = BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        } catch (Exception e) {
            // Toast.makeText(getApplicationContext(),
            // "Image File not found in your phone. Please select another image.",            // Toast.LENGTH_LONG).show();        }
        return m;

    }

    private void displayImage(Bitmap bitmap, File path) {
        ExifInterface exif = null;
        if (path != null) {

            try {
                if (path != null)
                    exif = new ExifInterface(path.getAbsolutePath());
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }

        writeFilesfromCamera(bitmap,path.getAbsolutePath());
//        filePath = path;    }
    public static Bitmap RotateBitmap(Bitmap source, float angle) {
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        Bitmap rotatedImg = Bitmap.createBitmap(source, 0, 0,
                source.getWidth(), source.getHeight(), matrix, true);
        source.recycle();
        return rotatedImg;

    }
}

Comments

Popular Post

Implement search functionality with help of edittext, rxjava and retrofit 2 in android.

QR code scanner using Zxing library. Scanner for android

Store GPS Location in image background android.

Shortcut for android for every version, android shortcut for oreo, android shortcut for nougat.