How to take a photo, save it and get the photo in Android

I've been searching the simple example to take a photo, and save it using URI and retrieve the photo for image processing , I've tried lot of example code, but none of them went smoothly.

Is there anyone have the example code?


define a variable like this

protected static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 0;

Use the code for calling camera from android.

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),"fname_" +        
                        String.valueOf(System.currentTimeMillis()) + ".jpg"));
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);

and in the class calling this override the onActivityResult function and enter the code below.

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

    if (resultCode == RESULT_OK) {
        if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {

            //use imageUri here to access the image

            Bundle extras = data.getExtras();


            Bitmap bmp = (Bitmap) extras.get("data");

            // here you will get the image as bitmap

          else if (resultCode == RESULT_CANCELED) {
            Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT);


there are several example to capture image and store it and open it...

1. Android Camera API - Tutorial

2. Android Developers

3. Camera Example on Github

4. Another Example

I had the same problem.

I was testing some codes from the internet, and couldn't find any. Then, I studied some basics codes from After that, I mixed two different codes and my one worked! Here it goes!

public class MainActivity extends AppCompatActivity {

    static final int PICTURE_RESULT = 1;
    String mCurrentPhotoPath;
    ContentValues values;
    private Uri file;
    ImageView imageView;
    Bitmap help1;

    ThumbnailUtils thumbnail;

    protected void onCreate(Bundle savedInstanceState) {
        imageView = (ImageView) findViewById(;
        values = new ContentValues();

    public void launch_camera(View v) {
        // the intent is my camera
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //getting uri of the file
        file = Uri.fromFile(getFile());

        //Setting the file Uri to my photo

            startActivityForResult(intent, PICTURE_RESULT);

    //this method will create and return the path to the image file
    private File getFile() {
        File folder = Environment.getExternalStoragePublicDirectory("/From_camera/imagens");// the file path

        //if it doesn't exist the folder will be created

        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_"+ timeStamp + "_";
        File image_file = null;

        try {
            image_file = File.createTempFile(imageFileName,".jpg",folder);
        } catch (IOException e) {

        mCurrentPhotoPath = image_file.getAbsolutePath();
        return image_file;

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == PICTURE_RESULT) {
            if(resultCode == Activity.RESULT_OK) {
                try {
                    help1 = MediaStore.Images.Media.getBitmap(getContentResolver(),file);
                    imageView.setImageBitmap( thumbnail.extractThumbnail(help1,help1.getWidth(),help1.getHeight()));
                }catch (Exception e){

the XML files just have a Button and a ImageView and do not forget to declare in your android manifest the permissions:

<uses-feature android:name=""    android:required="true" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"  />

for more informations a suggest:

please use the following code.

package com.example.stackoverflow;
import java.math.BigInteger;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;

public class MyCameraActivity extends Activity {
    private static final int CAMERA_REQUEST = 1888; 

    static String str_Camera_Photo_ImagePath = "";
    private static File f;
    private static int Take_Photo = 2;
    private static String str_randomnumber = "";
    static String str_Camera_Photo_ImageName = "";
    public static String str_SaveFolderName;
    private static File wallpaperDirectory;
    Bitmap bitmap;
    int storeposition = 0;
    public static GridView gridview;
    public static ImageView imageView;

    public void onCreate(Bundle savedInstanceState) {
        this.imageView = (ImageView)this.findViewById(;
        Button photoButton = (Button) this.findViewById(;
        photoButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                str_SaveFolderName = Environment
                        + "/rajeshsample";
                str_randomnumber = String.valueOf(nextSessionId());
                wallpaperDirectory = new File(str_SaveFolderName);
                if (!wallpaperDirectory.exists())
                str_Camera_Photo_ImageName = str_randomnumber
                        + ".jpg";
                str_Camera_Photo_ImagePath = str_SaveFolderName
                        + "/" + str_randomnumber + ".jpg";
                System.err.println(" str_Camera_Photo_ImagePath  "
                        + str_Camera_Photo_ImagePath);
                f = new File(str_Camera_Photo_ImagePath);
                startActivityForResult(new Intent(
                        MediaStore.EXTRA_OUTPUT, Uri.fromFile(f)),
                System.err.println("f  " + f);

    // used to create randon numbers
    public String nextSessionId() {
        SecureRandom random = new SecureRandom();
        return new BigInteger(130, random).toString(32);

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
        if (requestCode == Take_Photo) {
            String filePath = null;

            filePath = str_Camera_Photo_ImagePath;
            if (filePath != null) {
                Bitmap faceView = ( new_decode(new File(
                                filePath))); // ========================> good
                                                // lines


            } else {
                bitmap = null;

    public static Bitmap new_decode(File f) {

        // decode image size

        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        o.inDither = false; // Disable Dithering mode

        o.inPurgeable = true; // Tell to gc that whether it needs free memory,
                                // the Bitmap can be cleared

        o.inInputShareable = true; // Which kind of reference will be used to
                                    // recover the Bitmap data after being
                                    // clear, when it will be used in the future
        try {
            BitmapFactory.decodeStream(new FileInputStream(f), null, o);
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block

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

        // decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        // o2.inSampleSize=scale;
        o.inDither = false; // Disable Dithering mode

        o.inPurgeable = true; // Tell to gc that whether it needs free memory,
                                // the Bitmap can be cleared

        o.inInputShareable = true; // Which kind of reference will be used to
                                    // recover the Bitmap data after being
                                    // clear, when it will be used in the future
        // return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        try {

//          return BitmapFactory.decodeStream(new FileInputStream(f), null,
//                  null);
            Bitmap bitmap= BitmapFactory.decodeStream(new FileInputStream(f), null, null);
            System.out.println(" IW " + width_tmp);
            System.out.println("IHH " + height_tmp);           
               int iW = width_tmp;
                int iH = height_tmp;

               return Bitmap.createScaledBitmap(bitmap, iW, iH, true);

        } catch (OutOfMemoryError e) {
            // TODO: handle exception
            // clearCache();

            // System.out.println("bitmap creating success");
            return null;
            // System.runFinalization();
            // Runtime.getRuntime().gc();
            // System.gc();
            // decodeFile(f);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            return null;




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
    android:orientation="vertical" >

        android:text="photo" >

        android:src="@drawable/ic_action_search" >


Need Your Help

Choosing CMS vs Portal vs MVC+Components?

c# content-management-system components portal

I need some help figuring out whether it'd be a good idea to use a CMS or portal solution for my latest project, which is (currently) an ASP.NET MVC application that must serve multiple customers (...

Socket connect exception saying connection refused

java spring maven sockets intellij-idea

I am building a spring boot application, which has multiple micro-services which are being used by one main service. Services are created as maven modules and I am using intelliJ IDEA 15 with trial