Capture Image from Camera and Display in Activity Capture Image from Camera and Display in Activity android android

Capture Image from Camera and Display in Activity


Here's an example activity that will launch the camera app and then retrieve the image and display it.

package edu.gvsu.cis.masl.camerademo;import android.app.Activity;import android.content.Intent;import android.graphics.Bitmap;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.ImageView;public class MyCameraActivity extends Activity{    private static final int CAMERA_REQUEST = 1888;     private ImageView imageView;    private static final int MY_CAMERA_PERMISSION_CODE = 100;    @Override    public void onCreate(Bundle savedInstanceState)    {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        this.imageView = (ImageView)this.findViewById(R.id.imageView1);        Button photoButton = (Button) this.findViewById(R.id.button1);        photoButton.setOnClickListener(new View.OnClickListener()        {            @Override            public void onClick(View v)            {                if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)                {                    requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_PERMISSION_CODE);                }                else                {                    Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);                     startActivityForResult(cameraIntent, CAMERA_REQUEST);                }             }        });    }    @Override    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)    {        super.onRequestPermissionsResult(requestCode, permissions, grantResults);        if (requestCode == MY_CAMERA_PERMISSION_CODE)        {            if (grantResults[0] == PackageManager.PERMISSION_GRANTED)            {                Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();                Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);                 startActivityForResult(cameraIntent, CAMERA_REQUEST);            }            else            {                Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();            }        }    }    @Override    protected void onActivityResult(int requestCode, int resultCode, Intent data)    {          if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK)        {              Bitmap photo = (Bitmap) data.getExtras().get("data");             imageView.setImageBitmap(photo);        }      } }

Note that the camera app itself gives you the ability to review/retake the image, and once an image is accepted, the activity displays it.

Here is the layout that the above activity uses. It is simply a LinearLayout containing a Button with id button1 and an ImageView with id imageview1:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    >    <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/photo"></Button>    <ImageView android:id="@+id/imageView1" android:layout_height="wrap_content" android:src="@drawable/icon" android:layout_width="wrap_content"></ImageView></LinearLayout>

And one final detail, be sure to add:

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

and if camera is optional to your app functionality. make sure to set require to false in the permission. like this

<uses-feature android:name="android.hardware.camera" android:required="false"></uses-feature>

to your manifest.xml.


Update (2020)

Google has added a new ActivityResultRegistry API that "lets you handle the startActivityForResult() + onActivityResult() as well as requestPermissions() + onRequestPermissionsResult() flows without overriding methods in your Activity or Fragment, brings increased type safety via ActivityResultContract, and provides hooks for testing these flows" - source.

The API was added in androidx.activity 1.2.0-alpha02 and androidx.fragment 1.3.0-alpha02.

So you are now able to do something like:

val takePicture = registerForActivityResult(ActivityResultContracts.TakePicture()) { success: Boolean ->    if (success) {        // The image was saved into the given Uri -> do something with it    }}val imageUri: Uri = ...button.setOnClickListener {    takePicture.launch(imageUri)}

Take a look at the documentation to learn how to use the new Activity result API: https://developer.android.com/training/basics/intents/result#kotlin

There are many built-in ActivityResultContracts that allow you to do different things like pick contacts, request permissions, take pictures or take videos. You are probably interested in the ActivityResultContracts.TakePicture shown above.

Note that androidx.fragment 1.3.0-alpha04 deprecates the startActivityForResult() + onActivityResult() and requestPermissions() + onRequestPermissionsResult() APIs on Fragment. Hence it seems that ActivityResultContracts is the new way to do things from now on.


Original answer (2015)

It took me some hours to get this working. The code it's almost a copy-paste from developer.android.com, with a minor difference.

Request this permission on the AndroidManifest.xml:

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

On your Activity, start by defining this:

static final int REQUEST_IMAGE_CAPTURE = 1;private Bitmap mImageBitmap;private String mCurrentPhotoPath;private ImageView mImageView;

Then fire this Intent in an onClick:

Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);if (cameraIntent.resolveActivity(getPackageManager()) != null) {    // Create the File where the photo should go    File photoFile = null;    try {        photoFile = createImageFile();    } catch (IOException ex) {        // Error occurred while creating the File        Log.i(TAG, "IOException");    }    // Continue only if the File was successfully created    if (photoFile != null) {        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));        startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);    }}

Add the following support method:

private File createImageFile() throws IOException {    // Create an image file name    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());    String imageFileName = "JPEG_" + timeStamp + "_";    File storageDir = Environment.getExternalStoragePublicDirectory(            Environment.DIRECTORY_PICTURES);    File image = File.createTempFile(            imageFileName,  // prefix            ".jpg",         // suffix            storageDir      // directory    );    // Save a file: path for use with ACTION_VIEW intents    mCurrentPhotoPath = "file:" + image.getAbsolutePath();    return image;}

Then receive the result:

@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {        try {            mImageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath));            mImageView.setImageBitmap(mImageBitmap);        } catch (IOException e) {            e.printStackTrace();        }    }}

What made it work is the MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath)), which is different from the code from developer.android.com. The original code gave me a FileNotFoundException.


Capture photo + Choose from Gallery:

        a = (ImageButton)findViewById(R.id.imageButton1);        a.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                selectImage();            }        });    }    private File savebitmap(Bitmap bmp) {      String extStorageDirectory = Environment.getExternalStorageDirectory().toString();      OutputStream outStream = null;     // String temp = null;        File file = new File(extStorageDirectory, "temp.png");      if (file.exists()) {       file.delete();       file = new File(extStorageDirectory, "temp.png");      }      try {       outStream = new FileOutputStream(file);       bmp.compress(Bitmap.CompressFormat.PNG, 100, outStream);       outStream.flush();       outStream.close();      } catch (Exception e) {       e.printStackTrace();       return null;      }      return file;     }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.main, menu);        return true;    }     private void selectImage() {            final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);            builder.setTitle("Add Photo!");            builder.setItems(options, new DialogInterface.OnClickListener() {                @Override                public void onClick(DialogInterface dialog, int item) {                    if (options[item].equals("Take Photo"))                    {                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);                        File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");                        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));                        //pic = f;                        startActivityForResult(intent, 1);                    }                    else if (options[item].equals("Choose from Gallery"))                    {                        Intent intent = new   Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);                        startActivityForResult(intent, 2);                    }                    else if (options[item].equals("Cancel")) {                        dialog.dismiss();                    }                }            });            builder.show();        }        @Override        protected void onActivityResult(int requestCode, int resultCode, Intent data) {            super.onActivityResult(requestCode, resultCode, data);            if (resultCode == RESULT_OK) {                if (requestCode == 1) {                    //h=0;                    File f = new File(Environment.getExternalStorageDirectory().toString());                    for (File temp : f.listFiles()) {                        if (temp.getName().equals("temp.jpg")) {                            f = temp;                            File photo = new File(Environment.getExternalStorageDirectory(), "temp.jpg");                           //pic = photo;                            break;                        }                    }                    try {                        Bitmap bitmap;                        BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();                        bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),                                bitmapOptions);                         a.setImageBitmap(bitmap);                        String path = android.os.Environment                                .getExternalStorageDirectory()                                + File.separator                                + "Phoenix" + File.separator + "default";                        //p = path;                        f.delete();                        OutputStream outFile = null;                        File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");                        try {                            outFile = new FileOutputStream(file);                            bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);    //pic=file;                            outFile.flush();                            outFile.close();                        } catch (FileNotFoundException e) {                            e.printStackTrace();                        } catch (IOException e) {                            e.printStackTrace();                        } catch (Exception e) {                            e.printStackTrace();                        }                    } catch (Exception e) {                        e.printStackTrace();                    }                } else if (requestCode == 2) {                    Uri selectedImage = data.getData();                   // h=1;    //imgui = selectedImage;                    String[] filePath = { MediaStore.Images.Media.DATA };                    Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);                    c.moveToFirst();                    int columnIndex = c.getColumnIndex(filePath[0]);                    String picturePath = c.getString(columnIndex);                    c.close();                    Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));                    Log.w("path of image from gallery......******************.........", picturePath+"");                    a.setImageBitmap(thumbnail);                }            }