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);
}
}
Related
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)
I have a problem with Uri object. User should take a photo and next this is sending to Firebase Storage. But sth is wrong with onActivityResult.
I read a lot of topics (https://developer.android.com/training/camera/photobasics.html, StackOverFlow too) but nothing works with this code.
There is an error:
Attempt to invoke virtual method 'java.lang.String android.net.Uri.getLastPathSegment()' on a null object reference
Below is a code:
mUploadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
mProgress.setMessage("Uploading Image...");
mProgress.show();
Uri uri = data.getData();
StorageReference filepath = mStorage.child("Photos").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mProgress.dismiss();
Uri downloadUri = taskSnapshot.getDownloadUrl();
Picasso.with(MainActivity.this).load(downloadUri).fit().centerCrop().into(mImageView);
Toast.makeText(MainActivity.this, "Upload Done.", Toast.LENGTH_LONG).show();
}
});
}
}
}
As I checked, data (Intent) in onActivityResult is equal to NULL, so uri is null as well.
So, how can I resolve this challenge and make it usable? Should I use a Bitmap to have an access to a photo?
Could someone help me to resolve this situation?
Regards
I figured out with my question.
It works at now.
private ProgressDialog mProgress;
private Button mUploadBtn;
private ImageView mImageView;
Uri picUri;
private StorageReference mStorage;
private static final int CAMERA_REQUEST_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mStorage = FirebaseStorage.getInstance().getReference();
mUploadBtn = (Button) findViewById(R.id.uploadBtn);
mImageView = (ImageView) findViewById(R.id.imageView);
mProgress = new ProgressDialog(this);
mUploadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File file=getOutputMediaFile(1);
picUri = Uri.fromFile(file); // create
i.putExtra(MediaStore.EXTRA_OUTPUT,picUri); // set the image file
startActivityForResult(i, CAMERA_REQUEST_CODE);
}
});
}
/** Create a File for saving an image */
private File getOutputMediaFile(int type){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyApplication");
/**Create the storage directory if it does not exist*/
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
/**Create a media file name*/
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == 1){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".png");
} else {
return null;
}
return mediaFile;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK ) {
mProgress.setMessage("Uploading Image...");
mProgress.show();
Uri uri = picUri;
StorageReference filepath = mStorage.child("Photos").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mProgress.dismiss();
Uri downloadUri = taskSnapshot.getDownloadUrl();
Picasso.with(MainActivity.this).load(downloadUri).fit().centerCrop().into(mImageView);
Toast.makeText(MainActivity.this, "Upload Done.", Toast.LENGTH_LONG).show();
}
});
}
}
Always create your file and store the captured image using the path as follows
File photoFile = null;
mUploadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
ex.printStackTrace();
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
}
});
}
private File createImageFile() throws IOException {
// Create an image mSelectedFile name
String timeStamp = new SimpleDateFormat(Constants.PHOTO_DATE_FORMAT, Locale.ENGLISH).format(new Date());
String imageFileName = "IMG_" + timeStamp;
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File file = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
return file;
}
Then use this file "photoFile" and use it as needed in onActivityResult.
I faced the same problem before so i made sure that i check everything i can check when onActivityResult is called below is my code.
First i use this intent to capture image
File photoFile;
URI uri;
mUploadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePhotoIntent.resolveActivity(getPackageManager()) != null)
{
try
{
photoFile = Create_ImageFile();
}
catch (Exception e)
{
Log.e("file", e.toString());
}
if (photoFile != null)
{
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile.getAbsoluteFile()));
}
}
startActivityForResult(takePhotoIntent, CAMERA_REQUEST_CODE);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent)
{
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case CAMERA_REQUEST_CODE:
if (resultCode == Activity.RESULT_OK)
{
try
{
Uri selectedImageURI = null;
ByteArrayOutputStream bos;
Bitmap bitmap = null;
int orientation;
ExifInterface exif = null;
FileOutputStream fos = null;
bos = new ByteArrayOutputStream();
try
{
uri=imageReturnedIntent.getData();
selectedImageURI = imageReturnedIntent.getData();
bitmap= BitmapFactory.decodeFile(GetRealPathFromURI(selectedImageURI));
exif = new ExifInterface(GetRealPathFromURI(selectedImageURI));
fos = new FileOutputStream(GetRealPathFromURI(selectedImageURI));
}
catch (Exception e)
{
e.printStackTrace();
}
if(bitmap==null)
{
uri=Uri.fromFile(photoFile.getAbsoluteFile()));
bitmap=BitmapFactory.decodeFile(photoFile.getAbsolutePath());
exif = new ExifInterface(photoFile.getAbsolutePath());
fos = new FileOutputStream(photoFile.getAbsolutePath());
}
if(bitmap==null)
{
String imagePath = getPathGalleryImage(imageReturnedIntent);
bitmap = BitmapFactory.decodeFile(imagePath);
exif = new ExifInterface(imagePath);
fos = new FileOutputStream(imagePath);
}
Log.e("PhotoFile",photoFile.getAbsolutePath());
// Bitmap bitmap =(Bitmap) imageReturnedIntent.getExtras().get("data");
//bitmap = Bitmap.createScaledBitmap(bitmap,bitmap.getWidth(),bitmap.getHeight(), false);
orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
Log.e("ExifInteface .........", "rotation ="+orientation);
//exif.setAttribute(ExifInterface.ORIENTATION_ROTATE_90, 90);
Log.e("orientation", "" + orientation);
Matrix m = new Matrix();
if ((orientation == ExifInterface.ORIENTATION_ROTATE_180)) {
m.postRotate(180);
//m.postScale((float) bm.getWidth(), (float) bm.getHeight());
// if(m.preRotate(90)){
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), m, true);
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
m.postRotate(90);
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), m, true);
}
else if (orientation == ExifInterface.ORIENTATION_ROTATE_270)
{
m.postRotate(270);
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), m, true);
}
else
{
m.postRotate(0);
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), m, true);
}
//CropImage.activity(selectedImageURI).setGuidelines(CropImageView.Guidelines.ON).start(this);
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
userProfileIMG.setImageBitmap(bitmap);
StorageReference filepath = mStorage.child("Photos").child(uri.getLastPathSegment());
}
catch (Exception e)
{
e.printStackTrace();
}
}
break;
}
}
private String getPathGalleryImage(Intent imageURI)
{
Uri selectedImage = imageURI.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 imagePath = cursor.getString(columnIndex);
cursor.close();
return imagePath;
}
/**
* When image is returned we get its real path
**/
private String GetRealPathFromURI(Uri contentURI)
{
String result;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) {
// Source is Dropbox or other similar local file path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
private File Create_ImageFile() throws IOException
{
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String imageFileName = "JPEG_" + timeStamp;
File mediaStorageDir = getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = new File(mediaStorageDir.getAbsolutePath() + File.separator + imageFileName);
return image;
}
after this process i always ended having a bitmap to use it as i want.
For Get Actual Image predefined path of Captured Image using
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
this.startActivityForResult(cameraIntent, 101);
After Captured Image you can get Captured Image on path which is set in cameraIntent. If you don't Want to set predefined path then check Intent data.
if (resultCode == android.app.Activity.RESULT_OK && requestCode == 101) {
try {
path_mm = "Onsuccess_resultcode";
generateNoteOnSD("photo34.txt", path_mm);
Bitmap photo = null;
if (data == null) {
//get Bitmap here.
}
else {
Uri u1 = data.getData();
//get uri and find actual path on that uri.
}
}catch(Exception ex)
{}}
I've tried this but with no luck.
#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();
nameView.setText(selectedImage.toString());
realPath = getRealPathFromURI(this, selectedImage);
Toast.makeText(MainActivity.this, realPath, Toast.LENGTH_LONG).show();
}
}
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
I am getting null when I display in TOAST.
I am running Lollipop.
Please could someone explain in detail on how to do this.
I am able to get the URI without any problems but my only issue is to not being able to convert it to a real path to store in my database.
Thanks
This problem occurs mainly for google native devices such as Nexus because in these devices the only image library is google photos. In google photos you get to choose not only those images which are present on your device but also those photos which are stored on cloud storage too. Try the below mentioned updated code of yours and let me know if it worked or not.
Your intent should have action as Intent.ACTION_GET_CONTENT
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ATTACHMENT_PHOTO_GALLERY && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
nameView.setText(selectedImage.toString());
String realPath = getRealPathFromURI(this, selectedImage);
Toast.makeText(MainActivity.this, realPath, Toast.LENGTH_LONG).show();
}
}
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
String path = null;
try {
String[] proj = {MediaStore.Images.Media.DATA};
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
path = cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
//The above code will fail to get file path if the file is selected from google photos.
//Then this will be the alternative approach
if (path == null && contentUri.toString().startsWith("content://com.google.android.apps.photos.content")) {
Bitmap requiredImage = null;
//Below key should be used for saving the newly downloaded image path as
//photoIdentificationKey as Key parameter and newly generated path as Value.
//An additional check should be implemented on your storage that whether any local
//path exists for corresponding photoIdentificationKey, if yes then use the existing
//local path else download new image.
String photoIdentificationKey = Uri.parse(contentUri.getLastPathSegment()).getLastPathSegment();
BitmapFactory.Options options = new BitmapFactory.Options();
InputStream inputStream;
try {
inputStream = getApplication().getContentResolver().openInputStream(contentUri);
requiredImage = BitmapFactory.decodeStream(inputStream, null, options);
//Save the newly downloaded image to your isolated storage and return the path
//on which this new image has been saved.
inputStream.close();
path = saveAndReturnPathForSavedImage(requiredImage);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
return path;
}
private String saveAndReturnPathForSavedImage(Bitmap bmp) {
String path = Environment.getExternalStorageDirectory().toString();
OutputStream out = null;
File file = new File(path, "IMAGE"+ Calendar.getInstance().getTime()+".jpg"); // the File to save to
try {
out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return file.getPath();
}
If your Intent data data is not null then you can try this.
I've used this code to get image path from gallery, and its working in all devices.
Uri selectedImage = data.getData();
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.e("path of image from gallery......******************.........", picturePath + "");
Note: Be sure your data should not be null otherwise it will give NullPointerException.
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;
}
Hey, I am currently working on a live wallpaper and I allow the user to select an image which will go behind my effects.
Currently I have:
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
i.putExtra("crop", "true");
startActivityForResult(i, 1);
And slightly under that:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1)
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = data.getData();
Log.d("IMAGE SEL", "" + selectedImage);
// TODO Do something with the select image URI
SharedPreferences customSharedPreference = getSharedPreferences("imagePref", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = customSharedPreference.edit();
Log.d("HO", "" + selectedImage);
editor.putString("imagePref", getRealPathFromURI(selectedImage));
Log.d("IMAGE SEL", getRealPathFromURI(selectedImage));
editor.commit();
}
}
When my code is ran, Logcat tells me that selectedImage is null. If I comment out the
i.putExtra("crop", "true"):
Logcat does not give me the null pointer exception, and I am able to do what I want with the image. So, what is the problem here? Does any one have any idea how I can fix this? Thanks, for your time.
I have also faced this problem .You can try with this code. Its working fine for me
private static final String TEMP_PHOTO_FILE = "temporary_holder.jpg";
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
photoPickerIntent.setType("image/*");
photoPickerIntent.putExtra("crop", "true");
photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri());
photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
startActivityForResult(photoPickerIntent, REQ_CODE_PICK_IMAGE);
private Uri getTempUri() {
return Uri.fromFile(getTempFile());
}
private File getTempFile() {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File file = new File(Environment.getExternalStorageDirectory(),TEMP_PHOTO_FILE);
try {
file.createNewFile();
} catch (IOException e) {}
return file;
} else {
return null;
}
}
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case REQ_CODE_PICK_IMAGE:
if (resultCode == RESULT_OK) {
if (imageReturnedIntent!=null) {
File tempFile = getTempFile();
String filePath= Environment.getExternalStorageDirectory()
+"/"+TEMP_PHOTO_FILE;
System.out.println("path "+filePath);
Bitmap selectedImage = BitmapFactory.decodeFile(filePath);
_image = (ImageView) findViewById(R.id.image);
_image.setImageBitmap(selectedImage );
if (tempFile.exists()) tempFile.delete();
}
}
}
}
You don't need a Temp file:
protected static final int REQ_CODE_PICK_IMAGE = 1;
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
photoPickerIntent.setType("image/*");
photoPickerIntent.putExtra("crop", "true");
photoPickerIntent.putExtra("return-data", true);
photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
startActivityForResult(photoPickerIntent, REQ_CODE_PICK_IMAGE);
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case REQ_CODE_PICK_IMAGE:
if (resultCode == RESULT_OK) {
if (imageReturnedIntent!=null) {
Bundle extras = imageReturnedIntent.getExtras();
Bitmap selectedBitmap = extras.getParcelable("data");
imageR = (ImageView) findViewById(R.id.image);
imageR.setImageBitmap(selectedBitmap);
}
}
}
}
This code good with "beginners" ^^
private Bitmap FixBitmap;
Bitmap thePicBitmap;
String ImagePath = "image_path";
String ImagePath_1;
private static final String TEMP_PHOTO_FILE = "temporary_holder.jpg";
private static final int REQ_CODE_PICK_IMAGE = 0;
#Override
public void onClick(View view) {
try {
//intent = new Intent();
// intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//intent.setAction(Intent.ACTION_GET_CONTENT);
photoPickerIntent.setType("image/*");
photoPickerIntent.putExtra("crop", "true");
photoPickerIntent.putExtra("scale", true);
photoPickerIntent.putExtra("aspectX", 1);
photoPickerIntent.putExtra("aspectY", 1);
// indicate output X and Y
photoPickerIntent.putExtra("outputX", 150);
photoPickerIntent.putExtra("outputY", 100);
photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri());
photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
startActivityForResult(photoPickerIntent, REQ_CODE_PICK_IMAGE);
} catch (Exception e) {
// Toast.makeText(getApplicationContext(), R.string.imageException, Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
Toast toast = Toast.makeText(Upload_image_text.this, "This device doesn't support the crop action!",
Toast.LENGTH_SHORT);
toast.show();
}
}
private Uri getTempUri() {
return Uri.fromFile(getTempFile());
}
private File getTempFile() {
if (isSDCARDMounted()) {
File f = new File(Environment.getExternalStorageDirectory(),TEMP_PHOTO_FILE);
try {
f.createNewFile();
} catch (IOException e) {
}
return f;
} else {
return null;
}
}
private boolean isSDCARDMounted(){
String status = Environment.getExternalStorageState();
if (status.equals(Environment.MEDIA_MOUNTED))
return true;
return false;
}
});
=======================
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case REQ_CODE_PICK_IMAGE:
if (resultCode == RESULT_OK) {
if (imageReturnedIntent!=null){
// File tempFile = getTempFile();
ImagePath_1 = Environment.getExternalStorageDirectory()
+ "/temporary_holder.jpg";
System.out.println("path "+ImagePath_1);
FixBitmap = BitmapFactory.decodeFile(ImagePath_1);
ShowSelectedImage = (ImageView)findViewById(R.id.imageView);
ShowSelectedImage.setImageBitmap(FixBitmap);
}
}
}
}
===============================
#Override
protected String doInBackground(Void... params) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 1;
//options.outWidth = 50;
//options.outHeight = 50;
FixBitmap = BitmapFactory.decodeFile(ImagePath_1, options);
//FixBitmap = BitmapFactory.decodeResource(getResources(), R.id.imageView);
byteArrayOutputStream = new ByteArrayOutputStream();
FixBitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream); //compress to 50% of original image quality
byteArray = byteArrayOutputStream.toByteArray();
ConvertImage = Base64.encodeToString(byteArray, Base64.DEFAULT);