List All Camera Images in Android

List all camera images in Android

The Gallery app obtains camera images by using a content resolver over Images.Media.EXTERNAL_CONTENT_URI and filtering the results by Media.BUCKET_ID. The bucket identifier is determined with the following code:

public static final String CAMERA_IMAGE_BUCKET_NAME =
Environment.getExternalStorageDirectory().toString()
+ "/DCIM/Camera";
public static final String CAMERA_IMAGE_BUCKET_ID =
getBucketId(CAMERA_IMAGE_BUCKET_NAME);

/**
* Matches code in MediaProvider.computeBucketValues. Should be a common
* function.
*/
public static String getBucketId(String path) {
return String.valueOf(path.toLowerCase().hashCode());
}

Based on that, here's a snippet to get all camera images:

public static List<String> getCameraImages(Context context) {
final String[] projection = { MediaStore.Images.Media.DATA };
final String selection = MediaStore.Images.Media.BUCKET_ID + " = ?";
final String[] selectionArgs = { CAMERA_IMAGE_BUCKET_ID };
final Cursor cursor = context.getContentResolver().query(Images.Media.EXTERNAL_CONTENT_URI,
projection,
selection,
selectionArgs,
null);
ArrayList<String> result = new ArrayList<String>(cursor.getCount());
if (cursor.moveToFirst()) {
final int dataColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
do {
final String data = cursor.getString(dataColumn);
result.add(data);
} while (cursor.moveToNext());
}
cursor.close();
return result;
}

For more info, review the ImageManager and ImageList classes of the Gallery app source code.

How can I find out the camera images folder of an Android phone?

Use getExternalStoragePublicDirectory()

with parameter DIRECTORY_PICTURES

(or, for other use cases, other similar parameters such as DIRECTORY_MOVIES)

Function to get only camera image paths, not all images stored on android phone

Usually every Android device saves the camera images to DCIM directory. Here is a method that gets all the images saved in that directory.

public static List<String> getCameraImages(Context context) {
public final String CAMERA_IMAGE_BUCKET_NAME = Environment.getExternalStorageDirectory().toString()+ "/DCIM/Camera";

public final String CAMERA_IMAGE_BUCKET_ID = String.valueOf(CAMERA_IMAGE_BUCKET_NAME.toLowerCase().hashCode());

final String[] projection = { MediaStore.Images.Media.DATA };
final String selection = MediaStore.Images.Media.BUCKET_ID + " = ?";
final String[] selectionArgs = { CAMERA_IMAGE_BUCKET_ID };
final Cursor cursor = context.getContentResolver().query(Images.Media.EXTERNAL_CONTENT_URI,
projection,
selection,
selectionArgs,
null);
ArrayList<String> result = new ArrayList<String>(cursor.getCount());
if (cursor.moveToFirst()) {
final int dataColumn =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
do {
final String data = cursor.getString(dataColumn);
result.add(data);
} while (cursor.moveToNext());
}
cursor.close();
return result;
}

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.

Android Camera Image Name

How is this image name being generated?

That is up to the MediaStore. Use your original code, but use FileProvider to serve up access to the file location and get your Uri. See this sample app for how to use FileProvider with ACTION_IMAGE_CAPTURE.

Android - Get latest photos taken

I think this post https://stackoverflow.com/a/4495753/2014374 should help you finding your answer.

It used content resolver over Images.Media.EXTERNAL_CONTENT_URI and filters the results by getting the Media.BUCKET_ID from media bucket name "/DCIM/Camera"; Hope this helps.

in Android to show camera clicked images in horizontal scrolling view and into view dynamically.when u ckicked add into view

i have develop the solution..

        MainActivity.java
package com.example.mtk.recyclerviewdemo;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import static android.provider.MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE;
import static android.provider.MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO;
import static android.support.v4.app.ActivityCompat.startActivityForResult;

public class MainActivity extends AppCompatActivity {

static final int REQUEST_TAKE_PHOTO = 1;
private int SELECT_FILE = 2;
private static Button btnclick;
private String mCurrentPhotoPath;
private static RecyclerView recyclerView;
ArrayList<Data_Model> arrayList;
String chkpath = null;
MyAdapter m;
int i = 0;
private String userChoosenTask;
private Uri fileUri; // file url to store image/video

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

btnclick = (Button) findViewById(R.id.click);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);

arrayList = new ArrayList<>();
m = new MyAdapter();
Log.d("oncreate", "set adapter");
recyclerView.setAdapter(m);
ViewGroup.LayoutParams params = recyclerView.getLayoutParams();
params.height = 200;
recyclerView.setLayoutParams(params);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
recyclerView.setLayoutManager(linearLayoutManager);

//Camera Click image
btnclick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
selectImage();

}
});

}

public void takepicture() {
Log.d("Cameraclick", "takepicture");

Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}

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 = image.getAbsolutePath();
return image;

}

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

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

// Save Image To Gallery
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
String clickpath = mCurrentPhotoPath;
Data_Model data_model = new Data_Model();
data_model.setImage(clickpath);
arrayList.add(data_model);
m.notifyDataSetChanged();

} else if (requestCode == SELECT_FILE) {
Log.d("gallery", "checkpointd");
onSelectFromGalleryResult(data);
}
}

}

class MyAdapter extends RecyclerView.Adapter<MyAdapter.Myviewholder> {

@Override
public Myviewholder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = getLayoutInflater().inflate(R.layout.item_rowchk, parent, false);
Myviewholder myviewholder = new Myviewholder(v);
Log.d("myactivty ", "oncreateViewHolder");

return myviewholder;
}

@Override
public void onBindViewHolder(Myviewholder holder, final int position) {
final Data_Model m = arrayList.get(position);
Log.d(" myactivty", "onBindviewholder" + position);
//holder.imageView.setVisibility(View.VISIBLE);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 20;
final Bitmap bitmap = BitmapFactory.decodeFile(m.getImage(), options);
holder.imageView.setImageBitmap(bitmap);
holder.imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), ImageDisplay.class);
String chkpath = m.getImage();
intent.putExtra("path", chkpath);
Log.d("intent", "new activity");
startActivity(intent);
}
});
holder.imageView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {

final int pst = position;
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
arrayList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, arrayList.size());
// Yes button clicked
Toast.makeText(MainActivity.this, "Yes Clicked",
Toast.LENGTH_LONG).show();
break;

case DialogInterface.BUTTON_NEGATIVE:
// No button clicked
// do nothing
Toast.makeText(MainActivity.this, "No Clicked",
Toast.LENGTH_LONG).show();
break;
}
}
};

AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("Are you sure want to Delete ?")
.setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener).show();

return true;
}
});

}

@Override
public int getItemCount() {
return arrayList.size();
}

public class Myviewholder extends RecyclerView.ViewHolder {
public ImageView imageView;

public Myviewholder(View itemView) {
super(itemView);
imageView = (ImageView) itemView.findViewById(R.id.image);
}
}
}

private void onSelectFromGalleryResult(Intent data) {

Uri selectedImageUri = data.getData();
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(selectedImageUri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String path = cursor.getString(column_index);
Data_Model data_model = new Data_Model();
data_model.setImage(path);
arrayList.add(data_model);
m.notifyDataSetChanged();
// Toast.makeText(this, "" + path, Toast.LENGTH_LONG).show();
}

private void selectImage() {

final CharSequence[] items = {"Take Photo", "Choose from Library",
"Cancel"};

AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
boolean result = Utility.checkPermission(MainActivity.this);

if (items[item].equals("Take Photo")) {
userChoosenTask = "Take Photo";
if (result)
takepicture();

} else if (items[item].equals("Choose from Library")) {
userChoosenTask = "Choose from Library";
if (result)
galleryIntent();

} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}

public void galleryIntent() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
Log.d("gallery", "checkpointA");
startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
Log.d("gallery", "checkpointB");
}
}

Data_Model.Java
package com.example.mtk.recyclerviewdemo;

import android.net.Uri;

public class Data_Model {
private String image;

// Getter and Setter model for recycler view items

public String getImage() {
return image;
}

public void setImage(String image) {
this.image = image;
}

}
ImageDisplay.java

package com.example.mtk.recyclerviewdemo;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;

public class ImageDisplay extends AppCompatActivity {
ImageView imageView;
private String path;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_display);
imageView = (ImageView) findViewById(R.id.imageviewnew);
//setupActionBar();

// Get Image Path
path = getIntent().getExtras().getString("path");

// Get Image
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions. inJustDecodeBounds = false;
bmOptions. inSampleSize = 4;
bmOptions. inPurgeable = true ;
Bitmap bitmap = BitmapFactory.decodeFile(path, bmOptions);

// Display Image
imageView.setImageBitmap(bitmap);
}
}

xml.files

activity_image_display.xml
activity_main.xml
item_row.xml
item_rowchk.xml

activity_main.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:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.mtk.recyclerviewdemo.MainActivity"
android:weightSum="1">

<Button
android:id="@+id/click"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="10dp"
android:text="CLICK"
android:background="#fabdca"
android:textSize="27sp" />

<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="20dp" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BUTTON CHECK"/>

</LinearLayout>

item_rowchk.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
android:id="@+id/image"
android:rotation="90"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

</LinearLayout>

Imagedisplay.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:id="@+id/activity_image_display"
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"
tools:context="com.example.mtk.recyclerviewdemo.ImageDisplay">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:rotation="90"
android:id="@+id/imageviewnew" />

</LinearLayout>


Related Topics



Leave a reply



Submit