Pickup image from gallery in android 11 + (Access denid) - java

Despite getting the necessary access to the file in Android, when I select a photo from the gallery in Android 11 and above, Android shows the message access denied.
I just select the image and receive it as a bitmap.
I try thease
1
...
Manifest permissions:
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"
android:maxSdkVersion="32" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="29" />
Select image from gallery:
public void selectImageFromGallery(ImageView view) {
setResourceImg(view);
checkListener();
if (tempFileFromSource == null) {
try {
tempFileFromSource = File.createTempFile("choose", "png", mContext.getExternalCacheDir());
tempUriFromSource = Uri.fromFile(tempFileFromSource);
} catch (IOException e) {
e.printStackTrace();
}
}
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.putExtra(MediaStore.EXTRA_OUTPUT, tempUriFromSource);
if (fragment == null) {
mContext.startActivityForResult(intent, REQUEST_PICTURE_FROM_GALLERY);
} else {
fragment.startActivityForResult(intent, REQUEST_PICTURE_FROM_GALLERY);
}
}
On Activity Result:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if ((requestCode == REQUEST_PICTURE_FROM_GALLERY) && (resultCode == Activity.RESULT_OK)) {
Log.d(TAG, "Image selected from gallery");
imageActionListener.onImageSelectedFromGallery(data.getData(), tempFileFromSource);
} else if ((requestCode == REQUEST_PICTURE_FROM_CAMERA) && (resultCode == Activity.RESULT_OK)) {
Log.d(TAG, "Image selected from camera");
imageActionListener.onImageTakenFromCamera(tempUriFromSource, tempFileFromSource);
} else if ((requestCode == REQUEST_CROP_PICTURE) && (resultCode == Activity.RESULT_OK)) {
Toast.makeText(mContext, "uryyg: "+data.toString(), Toast.LENGTH_SHORT).show();
Log.d(TAG, "Image returned from crop");
imageActionListener.onImageCropped(tempUriFromCrop, tempFileFromCrop);
}
}
Crop selected image:
public void requestCropImage(Uri uri, int outputX, int outputY, int aspectX, int aspectY) {
checkListener();
if (tempFileFromCrop == null) {
try {
tempFileFromCrop = File.createTempFile("crop", "png", mContext.getExternalCacheDir());
tempUriFromCrop = Uri.fromFile(tempFileFromCrop);
} catch (IOException e) {
e.printStackTrace();
}
}
// open crop intent when user selects image
final Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
intent.putExtra("output", tempUriFromCrop);
intent.putExtra("outputX", outputX);
intent.putExtra("outputY", outputY);
intent.putExtra("aspectX", aspectX);
intent.putExtra("aspectY", aspectY);
intent.putExtra("scale", true);
intent.putExtra("noFaceDetection", true);
if (fragment == null) {
mContext.startActivityForResult(intent, REQUEST_CROP_PICTURE);
} else {
fragment.startActivityForResult(intent, REQUEST_CROP_PICTURE);
}
//Toast.makeText(mContext, "uri3: "+uri.toString(), Toast.LENGTH_SHORT).show();
}
And we return the uri of the cropped image in the cache to this method:
#Override
public void onImageCropped(Uri uri, File imageFile) {
try {
Uri selectedImage = uri;
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContext().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
// getting bitmap from uri
//Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
} catch (Exception e) {
e.printStackTrace();
}
}

You will need to use intent with an action set to Intent.ACTION_GET_CONTENT and set the type of this intent to match all the image files i.e. "image/*". If you want that user will able to select only specific image file formats like png or jpeg then use something like "image/png" or "image/jpeg".
The code below describes a fully working example that is tested on Android 12L.
Create intent like this
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
pickerActivityResultLauncher.launch(Intent.createChooser(intent, "Select a photo"));
Using the AndroidX activity result register
private ActivityResultLauncher<Intent> pickerActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
if(result.getResultCode() == RESULT_OK) {
// This is the URI for the selected photo from the user.
Uri photoUri = result.getData().getData();
// Set URI to the image view to display the image.
imageView.setImageURI(photoUri);
} else {
// Handle the no-image selection case.
}
});
If you want to use the old method (which has no guarantee that it works on every device) then you can use
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select a photo"), REQUEST_PICTURE_FROM_GALLERY)

Related

Android app crop photo

I have a question.
This is the code that my application already have and it works like this : takes photo >crop > upload.
I don't want to crop the photo .How can I do this? Just deleting the dispatchCropImageIntent method?
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(this.getClass().getSimpleName(), "onActivityResult");
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_IMAGE_CAPTURE) {
File imageFile = new File(mCurrentPhotoPath);
if (imageFile.exists()) {
dispatchCropImageIntent(Uri.fromFile(imageFile));
}
} else if (requestCode == REQUEST_IMAGE_FROM_GALLERY_SELECT) {
dispatchCropImageIntent(data.getData());
} else if (requestCode == REQUEST_PICTURE_CROP) {
String filePath = Environment.getExternalStorageDirectory()
+ "/temporary_holder.jpg";
setCurrentBitmap(BitmapFactory.decodeFile(filePath));
} else if(requestCode == CAMERA_ACTIVITY_CODE){
// Get path
String path = data.getStringExtra(CustomCamera.OUT_PATH);
// Read file
byte[] imgData = AppFS.readFileFromPath(path);
if (imgData != null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(imgData , 0, imgData.length);
// TODO: Do something with the image, it should be okay
//((ImageView)findViewById(R.id.img)).setImageBitmap(bitmap);
} else {
Log.e("Main", "Data is null");
}
}
}
else{
onBackPressed();
}
}
And :
private void dispatchCropImageIntent(Uri uri) {
Intent cropImageIntent = new Intent("com.android.camera.action.CROP");
cropImageIntent.setDataAndType(uri, "image/*");
cropImageIntent.putExtra("crop", "true");
cropImageIntent.putExtra("noFaceDetection", true);
cropImageIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
// retrieve data on return
cropImageIntent.putExtra("return-data", true);
File f = new File(Environment.getExternalStorageDirectory(),
"/temporary_holder.jpg");
try {
f.createNewFile();
} catch (IOException ex) {
Log.e("io", ex.getMessage());
}
uri = Uri.fromFile(f);
cropImageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(cropImageIntent, REQUEST_PICTURE_CROP);
}
If I understand you correctly,you want to make your app working like this: takes photo > upload. So, you need to replace dispatchCropImageIntent() with setCurrentBitmap() or upload methond.

onActivityResult not working on API 23

The onActivityResult method returns blank data or is not called when picking an image from Gallery. My implementation works fine on API 16, 17...22 but I am having problems with API 23. I read this article: https://guides.codepath.com/android/Accessing-the-Camera-and-Stored-Media , about permissions.
My client has tested the app on 3 phones running Android 6
and they all have the same behavior when picking a image. You can see an activity screenshot, there are 3 ImageButtons (a big one, and 2 small ones), when user clicks on an ImageButton the gallery is triggered for picking an image, when user picks an image the ImageButton just gets grey instead of showing the picked image.
////onclick method///photo2 is a imagebutton////SELECT_PICTURE2 is the code
photo2_evento.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
//startActivityForResult(Intent.createChooser(intent, "Escoge
una imagen"), SELECT_PICTURE2);
startActivityForResult(intent, SELECT_PICTURE2);
}
});
///onactivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
try{
Uri selectedImageUri = data.getData();
if (requestCode == SELECT_PICTURE1) {
photo1_path = getRealPathFromURI(selectedImageUri);
photo1_evento.setImageBitmap(decodeSampledBitmapFromResource(photo1_path, 400, 400));
}else if(requestCode == SELECT_PICTURE2){
photo2_path = getRealPathFromURI(selectedImageUri);
photo2_evento.setImageBitmap(decodeSampledBitmapFromResource(photo2_path, 100, 100));
}else if(requestCode == SELECT_PICTURE3){
photo3_path = getRealPathFromURI(selectedImageUri);
photo3_evento.setImageBitmap(decodeSampledBitmapFromResource(photo3_path, 100, 100));
}
}catch(Exception e){
e.printStackTrace();
}catch (OutOfMemoryError e) {
e.printStackTrace();
Toast.makeText(getBaseContext(),"memory error", Toast.LENGTH_LONG).show();
}
}
}
////decodeSampledBitmapFromResource is just a method provided by Google Android for sizing images.
////this method is for getting the URI path, I got this code from stackoverflow
public String getRealPathFromURI(Uri contentUri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = null;
try {
if (Build.VERSION.SDK_INT > 19) {
// Will return "image:x*"
String wholeID = DocumentsContract.getDocumentId(contentUri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
cursor = Publicar_Eventos.this.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, sel, new String[] { id }, null);
} else {
cursor = Publicar_Eventos.this.getContentResolver().query(contentUri,
projection, null, null, null);
}
} catch (Exception e) {
e.printStackTrace();
}catch (OutOfMemoryError e) {
e.printStackTrace();
Toast.makeText(getBaseContext(),"error de memoria", Toast.LENGTH_LONG).show();
}
String path = null;
try {
int column_index = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
path = cursor.getString(column_index).toString();
cursor.close();
} catch (NullPointerException e) {
e.printStackTrace();
}
return path;
}

Take pictures and saving to SD card

I am trying to develop an app where you can take pictures and then display them on screen or upload a picture from your SD card and display on screen. Currently I am app to upload and display it on screen however when i select the option to take a photo I am able to take the photo and click save, however, the photo will not display on the screen nor will it save to the SD card. Please help!
public class UploadActivity extends Fragment {
private Button bt_browse;
private ImageView iv_photo;
private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
private String uploadImagePath = "";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.upload,
container, false);
bt_browse = (Button) rootView.findViewById(R.id.button1);
iv_photo = (ImageView) rootView.findViewById(R.id.iv_photo);
bt_browse.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
selectImage();
}
});
return rootView;
}
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Select Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[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));
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[item].equals("Choose from Library")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(
Intent.createChooser(intent, "Select File"), SELECT_FILE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_CAMERA) {
File f = new File(Environment.getExternalStorageDirectory()
.toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bm;
BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
bm = BitmapFactory.decodeFile(f.getAbsolutePath(), btmapOptions);
bm = Bitmap.createScaledBitmap(bm, 70, 70, true);
iv_photo.setImageBitmap(bm);
uploadImagePath = f.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == SELECT_FILE) {
Uri selectedImageUri = data.getData();
String tempPath = getPath(selectedImageUri, getActivity());
Bitmap bm;
BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
bm = BitmapFactory.decodeFile(tempPath, btmapOptions);
iv_photo.setImageBitmap(bm);
uploadImagePath = tempPath;
}
}
}
#SuppressWarnings("deprecation")
public String getPath(Uri uri, Activity activity) {
String[] projection = { MediaColumns.DATA };
Cursor cursor = activity.managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
I have also added the following code to the Manifest file
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
i was handled this Scenario with this methods as:
private void getImageFromCamera() {
Log.i("GalaNotes", "From CAMERA Setting Capture TRUE");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "tmp_avatar_"
+ String.valueOf(System.currentTimeMillis()) + ".jpg"));
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
}
private void getImageFromGallery() {
Log.i("GalaNotes", "From Gallery Setting Capture TRUE");
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, PICK_FROM_FILE);
}
In the onActivityResult() method you can print the Uri or Path where it was stored as follows :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICK_FROM_CAMERA:
try {
log.i("Stored location of File",getRealPathFromURI(mImageCaptureUri));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case PICK_FROM_FILE:
mImageCaptureUri = data.getData();
Log.d("PHOTO", "" + mImageCaptureUri.toString()); // UPLOAD FEEDS
// RESPONSE
// doCrop();
Intent i = new Intent(activity, CropActivity.class);
try {
i.putExtra("imgSdcardPath", getRealPathFromURI(mImageCaptureUri));// mImageCaptureUri.toString());
startActivityForResult(i, 212);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}}
If You have any Query then givefeedback on my Post.
Try the standart way to get the photo from onActivityResult:
Bitmap imageBitmap = (Bitmap) data.getExtras().get("data");
// Global Declaration
Intent intent;
String imageFileName,videoFileName;
Uri uri;
private void clickPhotoFromCamera() {
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
imageFileName = "JPEG_" + timeStamp + ".jpg";
File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), imageFileName);
uri = Uri.fromFile(imageStorageDir);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intent, 1);
}
private void captureVideoFromCamera() {
intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
videoFileName = "VID_" + timeStamp + ".mp4";
File videoStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), videoFileName);
uri = Uri.fromFile(videoStorageDir);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intent, 2);
}
private void uploadMediaFromGallery() {
intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/* video/*");
startActivityForResult(intent, 3);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
imagePath = uri.getPath();
// Do whatever you want with image path...
} else if (requestCode == 2) {
videoPath = uri.getPath();
// Do whatever you want with Video path...
} else {
uri = data.getData();
mediaPath = getPath(getApplicationContext(), uri);
}
}
}
// For get Image or video from path...
File mediaFile = new File(mediaPath);
Bitmap bitmap;
if (mediaFile.exists()) {
if (isImage(mediaPath)) {
Bitmap myBitmap = BitmapFactory.decodeFile(mediaFile.getAbsolutePath());
int height = (myBitmap.getHeight() * 512 / myBitmap.getWidth());
Bitmap scale = Bitmap.createScaledBitmap(myBitmap, 512, height, true);
int rotate = 0;
try {
exif = new ExifInterface(mediaFile.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
switch (orientation) {
case ExifInterface.ORIENTATION_NORMAL:
rotate = 0;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
}
Matrix matrix = new Matrix();
matrix.postRotate(rotate);
Bitmap rotateBitmap = Bitmap.createBitmap(scale, 0, 0, scale.getWidth(), scale.getHeight(), matrix, true);
displayImage.setImageBitmap(rotateBitmap);
} else {
bitmap = ThumbnailUtils.createVideoThumbnail(mediaPath, Thumbnails.MICRO_KIND);
displayImage.setImageBitmap(bitmap);
}
}
public static boolean isImage(String str) {
boolean temp = false;
String[] arr = { ".jpeg", ".jpg", ".png", ".bmp", ".gif" };
for (int i = 0; i < arr.length; i++) {
temp = str.endsWith(arr[i]);
if (temp) {
break;
}
}
return temp;
}

UnsupportedOperationException Error while opening camera android

I am doing an Android application which need to open camera and display picture on screen and take that picture absolute path.
But I always get "UnsupportedOperationException: Unknown URI: content://media/external/images/media" error when I click on camera.
My code:
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "ircms");
imgUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); // Here getting error
Intent intentPicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intentPicture.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);
startActivityForResult(intentPicture, 1);
onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 1:
try {
String photoPath = getRealPathFromURI(this, imgUri);
o2.inSampleSize = 8;
Bitmap bitmap = BitmapFactory.decodeFile(photoPath, o2);
}
}
}
Please Help...
try this
What Do you Need
In Manafiest.xml
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
In your activity
private static final int TAKE_PHOTO_CODE = 1;
private void takePhoto(){
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(this)) );
startActivityForResult(intent, TAKE_PHOTO_CODE);
}
private File getTempFile(Context context){
//it will return /sdcard/image.tmp
final File path = new File( Environment.getExternalStorageDirectory(), context.getPackageName() );
if(!path.exists()){
path.mkdir();
}
return new File(path, "image.tmp");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch(requestCode){
case TAKE_PHOTO_CODE:
final File file = getTempFile(this);
try {
Bitmap captureBmp = Media.getBitmap(getContentResolver(), Uri.fromFile(file) );
// do whatever you want with the bitmap (Resize, Rename, Add To Gallery, etc)
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
Use this code to get file path of the image in onActivityResult
Uri selectedImageURI = data.getData();
imageFile = new File(getRealPathFromURI(selectedImageURI));
private String getRealPathFromURI(Uri contentURI) {
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
return contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
}

How to view the taken pictures in Android Without using Database?

Hai am new in Android Application.i Generated a code to take picture by using Camera.Now i want to view the Taken Pictures without using Database.i dont know how to do this.AnyBody please help me.
Thanks in advance
Here my Code
private void createCamera() {
// TODO Auto-generated method stub
preview = new Preview(this);
((FrameLayout) findViewById(R.id.preview)).addView(preview);
buttonClick = (Button) findViewById(R.id.buttonClick);
buttonClick.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
preview.camera.takePicture(shutterCallback, rawCallback, jpegCallback);
}
});
Log.d(TAG, "onCreate'd");
}
ShutterCallback shutterCallback = new ShutterCallback() {
public void onShutter() {
Log.d(TAG, "onShutter'd");
}
};
/** Handles data for raw picture */
PictureCallback rawCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
Log.d(TAG, "onPictureTaken - raw");
}
};
/** Handles data for jpeg picture */
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(String.format("/sdcard/%d.jpg", System.currentTimeMillis()));
outStream.write(data);
outStream.close();
Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {}
Log.d(TAG, "onPictureTaken - jpeg");
}
};
private void createpictures() {
img = (ImageView)findViewById(R.id.ImageView01);
((Button) findViewById(R.id.Button01)).setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
img.setImageURI(selectedImageUri);
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
Simple as this:
Intent in = new Intent(Intent.ACTION_VIEW, Uri.parse("file://"+yourFileName));
startActivity(in);
Default app for viewing pictures will start, or if there's no default, user get selection dialog which app to use.
you really dont need to use database to view taken picture.
To get new image - open an intent for Camera. like this
To see all other captured images, open Gallery. see this discussion
heres a good overview of opening data via intents on your phone. All this documentation is in here as well http://developer.android.com/guide/topics/intents/intents-filters.html but not as clear to follow.
http://indyvision.net/2010/03/android-using-intents-open-files/
File imageFile2View = new File("/sdcard/nice_photo.jpeg");
Intent i = new Intent();
i.setAction(android.content.Intent.ACTION_VIEW);
i.setDataAndType(Uri.fromFile(imageFile2View), "image/jpeg");
startActivity(i);
Now if what your looking for is to display the picture you took in your own activity you can use.
String file = String.format("/sdcard/%d.jpg", System.currentTimeMillis());
//SAVE IMAGE TO file
img.setImageURI(URI.parse(file));
or
String file = String.format("/sdcard/%d.jpg", System.currentTimeMillis());
//SAVE IMAGE TO file
bitmap = BitmapFactory.decodeFile(file);
img.setImageBitmap(bitmap);

Categories