Load image from sdcard to imageview not working - android

Tried many methods, but did not reach a positive outcome.
In TableLayout has ImageView:
<TableLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/photo_layout_background"
android:stretchColumns="*" >
<TableRow
android:background="#color/photo_layoutrow_background"
android:layout_weight="1"
android:layout_marginBottom="4dp"
android:gravity="center" >
<ImageView
android:id="#+id/photo1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginRight="4dp"
android:src="#drawable/icon_photo"
android:background="#color/photo_background"
android:clickable="true"
android:onClick="addPhoto_Click"/>
When you click on ImageView offer standard procedure for obtaining pictures and the file is saved on the SD card:
public void addPhoto_Click(View v){
select_add_photo_id = v.getId();
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, generateFilePhotoUri());
startActivityForResult(takePictureIntent, CAMERA_RESULT);
}
#SuppressLint("SimpleDateFormat")
private Uri generateFilePhotoUri() {
File file = null;
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
file = new File(MEDIA_PATH + String.valueOf(id) + File.separator + timeStamp + ".jpg");
select_add_photo_file = file.getAbsolutePath();
return Uri.fromFile(file);
}
The photo is saved normally stored in variables select_add_photo_id id ImageView on which tapped the select_add_photo_file variable holds the full path to the file photo.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_RESULT) {
if (resultCode == RESULT_OK){
ImageView imgView = (ImageView) findViewById(select_add_photo_id);
imgView.setImageDrawable(Drawable.createFromPath(select_add_photo_file));
}
}
}
But when the file is only get ImageView ImageView with background and increased size. Photography is not loaded. There are no errors.
As still set photos?

after take a phone, in onActivityResult, data.getData may be null, in this case, try data.getExtras()
Bitmap photo = null;
Uri photoUri = data.getData();
String filePath = "";
if (photoUri != null) {
//mFilePath = getRealPathFromURI(photoUri);
filePath = getRealPathFromURI(photoUri);
photo = BitmapFactory.decodeFile(photoUri.getPath());
}
if (photo == null) {
Bundle extra = data.getExtras();
if (extra != null) {
photo = (Bitmap)extra.get("data");
...

Related

Image loses it's original result when passing it to another activity

I am working on a camera feature in my application. I am capturing an image and passing it to another activity. The problem that I'm facing is when I display the image in another activity it loses its original result (gets pixilated) for some reason. This is how I'm doing it:
private void takePhotoFromCamera() {
if(ActivityCompat.checkSelfPermission(EnterDataView.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED){
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}else {
String[] permissionRequest = {Manifest.permission.CAMERA};
requestPermissions(permissionRequest, 8675309);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK || resultCode != RESULT_CANCELED){
if(requestCode == CAMERA_REQUEST){
Bitmap mphoto = (Bitmap) data.getExtras().get("data");
Intent passPhoto = new Intent(this, Photo.class);
passPhoto.putExtra("byteArray",mphoto);
passPhoto.putExtra("Caller", getIntent().getComponent().getClassName());
startActivity(passPhoto);
}
}
}
Getting the image in other activity like this:
if(getIntent().hasExtra("byteArray")) {
//ImageView _imv= new ImageView(this);
/*Bitmap _bitmap = BitmapFactory.decodeByteArray(
getIntent().getByteArrayExtra("byteArray"),0,getIntent().getByteArrayExtra("byteArray").length);*/
Intent intent_camera = getIntent();
Bitmap camera_img_bitmap = (Bitmap) intent_camera
.getParcelableExtra("byteArray");
//_imv.setImageBitmap(_bitmap);
View view = mInflater.inflate(R.layout.gallery_item, mGallery, false);
ImageView img = (ImageView) view
.findViewById(R.id.id_index_gallery_item_image);
//String uri = getPhotos.getString(getPhotos.getColumnIndex(("uri")));
//Uri mUri = Uri.parse(uri);
//img.setImageURI(mUri);
//byte[] blob = getPhotos.getBlob(getPhotos.getColumnIndex("image"));
//Bitmap bmp = BitmapFactory.decodeByteArray(blob, 0, blob.length);
//bmpImage.add(bmp);
img.setImageBitmap(camera_img_bitmap);
mGallery.addView(view);
}
My XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/id_index_gallery_item_image"
android:layout_width="#dimen/_300sdp"
android:layout_height="#dimen/_300sdp"
android:layout_alignParentTop="true"
android:layout_marginLeft="#dimen/_10sdp"
android:layout_marginTop="#dimen/_50sdp"
android:scaleType="centerCrop" />
</RelativeLayout>
What Am I doing wrong?
The method which you have used will not work on all the devices above marshmallow.
Follow this,
add this in your manifest.xml
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="yourpackagename.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_path"/>
</provider>
create provider_path in xml folder of your resources.
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="/storage/emulated/0" path="."/>
</paths>
then add this in your activity,
declare a global variable
private Uri mUri;
private static final String CAPTURE_IMAGE_FILE_PROVIDER = "com.yourpackagename.fileprovider";
private void takePicture() {
File file = null;
try {
file = createImageFile();
mUri = FileProvider.getUriForFile(context,
CAPTURE_IMAGE_FILE_PROVIDER, file);
Log.d("uri", mUri.toString());
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
startActivityForResult(cameraIntent, REQUEST_CAMERA_STORAGE);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CAMERA_STORAGE) {
if (resultCode == RESULT_OK) {
if (mUri != null) {
String profileImageFilepath = mUri.getPath().replace("//", "/");
sendImage(profileImageFilepath);
}
} else {
Toast.makeText(context, "Picture wasn't taken!", Toast.LENGTH_SHORT).show();
}
}
}
this is createImageFile()
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "APPNAME-" + timeStamp + ".png";
File mediaStorageDir = new File(Environment.getExternalStorageDirectory(),
"FOLDERNAME");
File storageDir = new File(mediaStorageDir + "/Images");
if (!storageDir.exists()) {
storageDir.mkdirs();
}
File image = new File(storageDir, imageFileName);
return image;
}
and finally, pass profileImageFilepath to our next activity to display
In this line I get error:
private static final String CAPTURE_IMAGE_FILE_PROVIDER =
"com.yourpackagename.fileprovider";
This line is correct:
private static final String CAPTURE_IMAGE_FILE_PROVIDER =
"com.yourpackagename.provider";
instead fileprovider write provider or use this
mUri = FileProvider.getUriForFile(MainActivity.this,
BuildConfig.APPLICATION_ID + ".provider", file);
My problem is solved. Thank you very much.
Very good work.

Take photo intent returns null on data

I'm creating an app to take photos and delete image from gallery after specific process. Here is my code
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivityForResult(takePictureIntent, requestCode);
}
And I handle the result just like this
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
image1 = (Bitmap) extras.get(IMAGE_BUNDLE_NAME);
imageView1.setImageBitmap(image1);
imageUri1 = data.getData();
}
}
The problem is that data.getData(); returns null in some devices. I tried to replace URI with this code
imageUri1 = getImageUri(getActivity(), image1);
And this method
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
Whe I use this Uri I can't delete file from device. This is how I delete images
private void deleteFileFromMediaStore(final ContentResolver contentResolver, int requestCode) {
String canonicalPath;
File fdelete = new File(imageUri1.getPath());
if(fdelete != null){
try {
canonicalPath = fdelete.getCanonicalPath();
} catch (IOException e) {
canonicalPath = fdelete.getAbsolutePath();
}
final Uri uri = MediaStore.Files.getContentUri(Constants.EXTERNAL_STORAGE_CONSTANT);
final int result = contentResolver.delete(uri,
MediaStore.Files.FileColumns.DATA + "=?", new String[] {canonicalPath});
if (result == 0) {
final String absolutePath = fdelete.getAbsolutePath();
if (!absolutePath.equals(canonicalPath)) {
contentResolver.delete(uri,
MediaStore.Files.FileColumns.DATA + "=?", new String[]{absolutePath});
}
}
}
}
How can I delete the photo or how can I make data.getData() non null on all devices?
The problem is that data.getData(); returns null in some devices
It will return null with most camera apps, as it is supposed to return null.
How can I delete the photo
Save the thumbnail photo to a file (compress() and a FileOutputStream).
Or, use EXTRA_OUTPUT to request that the camera app save a full-size photo to a location that you specify (e.g., using a FileProvider-supplied Uri).
Or, use a library like Fotoapparat to take photos directly in your app, rather than relying on one of hundreds of camera apps.
how can I make "data.getData()" non null on all devices?
You can't.

Image size and dimensions reduce when I capture from camera

Using this to open camera:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
and in OnActivityResult:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data != null) {
if (requestCode == REQUEST_CAMERA && resultCode == RESULT_OK)
{
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
if (data != null) {
cameraBitMap = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
cameraBitMap.compress(Bitmap.CompressFormat.JPEG,100, bytes);
cameraFilePath = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
cameraFilePath.createNewFile();
fo = new FileOutputStream(cameraFilePath);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(cameraFilePath.getAbsolutePath(), options);
imageHeight = options.outHeight;
imageWidth = options.outWidth;
camImagePath = String.valueOf(cameraFilePath);
String fileName = camImagePath.substring(camImagePath.lastIndexOf("/") + 1);
txt_FileName.setText(fileName);
txt_FileName.setVisibility(View.VISIBLE);
btn_ImageTest.setImageBitmap(cameraBitMap);
}
}
I want the original size image to display when I capture it from the camera.
Use Intent like this. Here first give image name .
//declare globally
private static final int CAMERA_CODE = 101 ;
private Uri mImageCaptureUri;
Start Intent as below.
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp1.jpg");
if (f.exists()) {
f.delete();
}
mImageCaptureUri = Uri.fromFile(f);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
startActivityForResult(intent, CAMERA_CODE);
And in onActivityResult :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_CODE && resultCode == RESULT_OK) {
System.out.println("Camera Image URI : " + mImageCaptureUri);
String path = mImageCaptureUri.getPath();
if (new File(path).exists()) {
Toast.makeText(MainActivity.this, "Path is Exists..", Toast.LENGTH_LONG).show();
}
btn_ImageTest.setImageURI(mImageCaptureUri);
}
}
You need to create temporary file before you start Camera Activity Intent.
Anything that using below code or similar like that after you take image using camera actually is a thumbnail image which is reduced the original quality.
This is the code that I meant:
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(imageBitmap);
Refer Here for more info
This are the solution that you want
First You need to create temporary file.
Convert the temporary file into URI
Pass URI data to Camera intent by using putExtra method.
Open Camera Activity intent.
Handle onActivityResult if user cancel or accept the image from Camera Activity intent.
Below are the method you can use for step by step mentioned above.
Create Temporary File.
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 = getExternalFilesDir(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;
}
Convert Temporary file to URI and invoke camera activity intent.
static final int REQUEST_TAKE_PHOTO = 1;
Uri photoURI;
File photoFile;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
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) {
photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
Now you already have File location path created before Camera Activity intent called. You can handle RESULT_OK(Show image) or RESULT_CANCELED(Delete temporary image).
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
mImageView.setImageURI(photoURI );
}else{
photoFile.delete();
}
}
*Take note on getUriForFile which returns a content:// URI. For more recent apps targeting Android 7.0 (API level 24) and higher, passing a file:// URI across a package boundary causes a FileUriExposedException. Therefore, we now present a more generic way of storing images using a FileProvider.
Full documentation is here for reference.
Taking Photo Simply

Unable to use intent for CAMERA

In my application ,on clicking Image View i want to start Camera which will capture image and display it in another image view.My code is given below:
//On clicking Camera
iv_camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
if (data != null) {
Log.e("Result Code", String.valueOf(resultCode));
Bitmap photo = (Bitmap) data.getExtras().get("data");
Uri selectedImageUri = data.getData();
Log.e("ImageUri", String.valueOf(selectedImageUri));
String realPath = getRealPathFromURI(selectedImageUri);
Log.e("Real Path", realPath);
imgProfilePic.setImageBitmap(photo);
}
}
}
//Get real path form Uri
public String getRealPathFromURI(Uri contentUri) {
try {
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} catch (Exception e) {
return contentUri.getPath();
}
}
My problem is that ,on some mobiles it is working fine but on some it is not. For example: If i am testing my application using on my phone Yu Yureka having Lollipop ,it is giving me data as null.Also when the orientation changes,application is crashing .Please help me to fix the issue.
In your Manifest file use these permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Implement from this Simple Code Example this is my working example code
public void CameraClick(View v) {
Intent intent= new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// creating Dir to save clicked Photo
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/cam_Intent");
myDir.mkdirs();
// save clicked pic to given dir with given name
File file = new File(Environment.getExternalStorageDirectory(),
"/cam_Intent/MyPhoto.jpg");
outPutfileUri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outPutfileUri);
startActivityForResult(intent, TAKE_PIC);
}
Bitmap bitmap = null;
#Override
protected void onActivityResult(int requestCode, int resultCode,Intent data)
{
if (requestCode == TAKE_PIC && resultCode==RESULT_OK) {
String uri = outPutfileUri.toString();
Log.e("uri-:", uri);
Toast.makeText(this, outPutfileUri.toString(),Toast.LENGTH_LONG).show();
//Bitmap myBitmap = BitmapFactory.decodeFile(uri);
// mImageView.setImageURI(Uri.parse(uri)); OR drawable make image strechable so try bleow also
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), outPutfileUri);
Drawable d = new BitmapDrawable(getResources(), bitmap);
mImageView.setImageDrawable(d);
} catch (IOException e) {
e.printStackTrace();
}
}
}

Get file path of image on Android

I have an app that can make pictures and upload them. The upload requires the file path of the photo but I can't get it.
This is my code:
public void maakfoto (View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
knop.setVisibility(Button.VISIBLE);
System.out.println(mImageCaptureUri);
}
}
Please help me to get the file path.
Posting to Twitter needs the image's actual path on the device to be sent in the request to post. I was finding it mighty difficult to get the actual path and more often than not I would get the wrong path.
To counter that, once you have a Bitmap, I use that to get the URI from using the getImageUri(). Subsequently, I use the tempUri Uri instance to get the actual path as it is on the device.
This is production code and naturally tested. ;-)
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
knop.setVisibility(Button.VISIBLE);
// CALL THIS METHOD TO GET THE URI FROM THE BITMAP
Uri tempUri = getImageUri(getApplicationContext(), photo);
// CALL THIS METHOD TO GET THE ACTUAL PATH
File finalFile = new File(getRealPathFromURI(tempUri));
System.out.println(mImageCaptureUri);
}
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
Try out with mImageCaptureUri.getPath(); By Below Way :
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
//Get your Image Path
String Path=mImageCaptureUri.getPath();
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
knop.setVisibility(Button.VISIBLE);
System.out.println(mImageCaptureUri);
}
In order to take a picture you have to determine a path where you would like the image saved and pass that as an extra in the intent, for example:
private void capture(){
String directoryPath = Environment.getExternalStorageDirectory() + "/" + IMAGE_DIRECTORY + "/";
String filePath = directoryPath+Long.toHexString(System.currentTimeMillis())+".jpg";
File directory = new File(directoryPath);
if (!directory.exists()) {
directory.mkdirs();
}
this.capturePath = filePath; // you will process the image from this path if the capture goes well
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra( MediaStore.EXTRA_OUTPUT, Uri.fromFile( new File(filePath) ) );
startActivityForResult(intent, REQUEST_CAPTURE);
}
I just copied the above portion from another answer I gave.
However to warn you there are a lot of inconsitencies with image capture behavior between devices that you should look out for.
Here is an issue I ran into on some HTC devices, where it would save in the location I passed and in it's default location resulting in duplicate images on the device:
Deleting a gallery image after camera intent photo taken
I am doing this on click of Button.
private static final int CAMERA_PIC_REQUEST = 1;
private View.OnClickListener OpenCamera=new View.OnClickListener() {
#Override
public void onClick(View paramView) {
// TODO Auto-generated method stub
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
NewSelectedImageURL=null;
//outfile where we are thinking of saving it
Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
String newPicFile = RecipeName+ df.format(date) + ".png";
String outPath =Environment.getExternalStorageDirectory() + "/myFolderName/"+ newPicFile ;
File outFile = new File(outPath);
CapturedImageURL=outFile.toString();
Uri outuri = Uri.fromFile(outFile);
cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, outuri);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
};
You can get the URL of the recently Captured Image from variable CapturedImageURL
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//////////////////////////////////////
if (requestCode == CAMERA_PIC_REQUEST) {
// do something
if (resultCode == RESULT_OK)
{
Uri uri = null;
if (data != null)
{
uri = data.getData();
}
if (uri == null && CapturedImageURL != null)
{
uri = Uri.fromFile(new File(CapturedImageURL));
}
File file = new File(CapturedImageURL);
if (!file.exists()) {
file.mkdir();
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+Environment.getExternalStorageDirectory())));
}
}
}
use this function to get the capture image path
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Uri mImageCaptureUri = intent.getData();
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
knop.setVisibility(Button.VISIBLE);
System.out.println(mImageCaptureUri);
//getImgPath(mImageCaptureUri);// it will return the Capture image path
}
}
public String getImgPath(Uri uri) {
String[] largeFileProjection = { MediaStore.Images.ImageColumns._ID,
MediaStore.Images.ImageColumns.DATA };
String largeFileSort = MediaStore.Images.ImageColumns._ID + " DESC";
Cursor myCursor = this.managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
largeFileProjection, null, null, largeFileSort);
String largeImagePath = "";
try {
myCursor.moveToFirst();
largeImagePath = myCursor
.getString(myCursor
.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA));
} finally {
myCursor.close();
}
return largeImagePath;
}
You can do like that In Kotlin If you need kotlin code in the future
val myUri = getImageUri(applicationContext, myBitmap!!)
val finalFile = File(getRealPathFromURI(myUri))
fun getImageUri(inContext: Context, inImage: Bitmap): Uri {
val bytes = ByteArrayOutputStream()
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes)
val path = MediaStore.Images.Media.insertImage(inContext.contentResolver, inImage, "Title", null)
return Uri.parse(path)
}
fun getRealPathFromURI(uri: Uri): String {
val cursor = contentResolver.query(uri, null, null, null, null)
cursor!!.moveToFirst()
val idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA)
return cursor.getString(idx)
}
To get the path of all images in android I am using following code
public void allImages()
{
ContentResolver cr = getContentResolver();
Cursor cursor;
Uri allimagessuri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Images.Media._ID + " != 0";
cursor = cr.query(allsongsuri, STAR, selection, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
String fullpath = cursor.getString(cursor
.getColumnIndex(MediaStore.Images.Media.DATA));
Log.i("Image path ", fullpath + "");
} while (cursor.moveToNext());
}
cursor.close();
}
}
Simple Pass Intent first
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
And u will get picture path on u onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}

Categories

Resources