When the user takes a picture with the camera, I want the image displayed in an ImageView and I want to save the Uri to an online database. I heard saving the Uri of a picture is better than saving the path.
So this is how I start the camera:
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getFile(getActivity())));
String a = String.valueOf(Uri.fromFile(getFile(getActivity())));
intent.putExtra("photo_uri", a);
startActivityForResult(intent, PICK_FROM_CAMERA);
where
private File getFile(Context context){
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File (sdCard.getAbsolutePath() + "/Myapp");
if (!directory.exists()) {
directory.mkdirs();
}
String filename = "bl" + System.currentTimeMillis() + ".jpg";
File newFile = new File(directory, filename);
return newFile;
}
In onActivityResult:
Bundle extras = data.getExtras();
String photo_uri = extras.getString("photo_uri"); //null
This is always null. Btw before sending the intent the Uri looks like file://... instead of content:// which is the uri when I open an image from the gallery. I don't know if that's a problem.
Also, should I save the path instead of the Uri to the database? I read that the Uri can be complicated in certain phones or Android versions. When I let the user select an image from the gallery, I save the Uri to the database, so I think the best way is saving the Uri in this case as well.
I tried out many variations, but I get null every time I try to pass a variable with the intent...
After starting the intent:
Intent intentPicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intentPicture,PICK_FROM_CAMERA);
In onActivityResult:
case PICK_FROM_CAMERA:
Uri selectedImageUri = data.getData();
InputStream imageStream = null;
try {
imageStream = getContentResolver().openInputStream(selectedImageUri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
break;
That's all.
Related
I've found ways that have supposedly worked for people to retrieve the uri/bitmap of the camera taken image.
But when I try and create a bitmap out of the non-null uri that I'm getting the file isn't created and doesn't exist.
this the the function which I use to open the camera intent(Which is copied from stackoverflow):
private void openBackCamera() {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = timeStamp + ".jpg";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
currentImageBase64 = storageDir.getAbsolutePath() + "/" + imageFileName;
File file = new File(currentImageBase64);
Log.d("2","file 1: " +file.exists());
Uri outputFileUri = FileProvider.getUriForFile(getApplicationContext(),"com.mydomain.fileprovider",file);
currentImageBase64 =outputFileUri+"";
Log.d("2",outputFileUri+" is the uri got from camera");
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
and this is how I handel my images:
Log.d("2","camera request!"+ currentImageBase64);
File imgFile = new File(currentImageBase64);
if(imgFile.exists()) {
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ivPreview.setImageBitmap(myBitmap);
}else{
Log.d("2","file does not exist");
}
note that the camera request log shows that currentImagesBase64 is not null and has a value "content://com.mydomain.fileprovider/name/Pictures/20190121_173332.jpg"
the file anyway, does not exist.
/**
edit: the problem was insufficent permissions, camera and read&write permissions were requested and the problem was resolved!
**/
Turn out Permissions were the problem, once I gave runtime camera read&write storage permissions the problem was fixed!
I can't get my ImageViews to update from either URI or file path - they just don't show an image
Intent to capture image:
Intent photo = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(photo, 1);
On ActivityResult
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
Uri imageUri = data.getData();
filePath = getRealPathFromURI(this, imageUri);
}
GetRealPathFromURI class:
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();
}
}
}
It then inserts 'filePath' from onActivityResult in to a db
Retrieving from db and updating ImageViews
imgfilepath[y] = cursorc.getString(cursorc.getColumnIndex("IMAGE"));
imgFile[y] = new File(imgfilepath[y]);
Uri uri = Uri.fromFile(imgFile[y]);
String path = uri.getPath();
mImage.setImageURI(uri);
I've tried so many different ways to setImageBitmap etc which haven't worked (I can't remember all of them) - Can anyone see why this is not showing the image?
The image is in emulated storage and not the SD card.
EDIT:
I've added EXTRA_OUTPUT tag but I can't see the image in DDMS anywhere & the camera does not exit after taking the picture/accepting the image
Intent photo = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
final File root = new File(Environment.getExternalStorageDirectory() + File.separator + "MyDir" + File.separator);
root.mkdirs();
final String fname = "img_"+ System.currentTimeMillis() + ".jpg";
final File sdImageMainDirectory = new File(root, fname);
mImageUri = Uri.fromFile(sdImageMainDirectory);
photo.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
startActivityForResult(photo, 1);
Uri imageUri = data.getData();
ACTION_IMAGE_CAPTURE does not return a Uri.
The image is in emulated storage
Perhaps that one camera app does, in which case that camera app has a bug, to go along with the return-a-Uri bug.
There are thousands of Android device models. These ship with hundreds of different camera apps pre-installed, and there are hundreds more available from the Play Store and elsewhere. Many will have ACTION_IMAGE_CAPTURE implementations. Most should follow the documented protocol. None should save the image for your request, because you did not tell the camera app where to save the image.
Either:
Provide a location, via EXTRA_OUTPUT, for the camera app to save the image to, then load the image from that location, or
Use data.getExtra("data") to get a Bitmap that represents a thumbnail-sized image, if you do not provide EXTRA_OUTPUT
I’m using some big pictures that are stored in External Memory. I decode them, resize them and set the small bitmaps to various imageviews.
I keep track of those large images by storing their Uri’s. When the app stops, I convert Uri to paths and save them as Strings is a SQLite base:.
File myFile = new File(provider.getImageUri().toString());
cv.put(DBHelper.DB_IMAGEPATH, myFile.getAbsolutePath());
At this point the path to the image looks like:
/content/media/.. and everything works ok.
When the app resumes I read the path from database and convert it to Uri:
File tempFile = new File(cursor.getString(imagePathColIndex);
mUri = (Uri.fromFile(mFile));
Now the path in new mUri looks like:
File:///content/... And there is a IONotFound exception.
You should try with
File tempFile = new File(cursor.getString(imagePathColIndex));
mUri = Uri.parse(tempFile.getAbsolutePath());
Testing with the following code
String path = "/content/media";
Uri uri = Uri.fromFile(new File(path));
Log.e(TAG, uri.toString()); //print file:///content/media
uri = Uri.parse(path);
Log.e(TAG, uri.toString()); //print /content/media
EDIT
To read the image can you try
BitmapFactory.decodeStream(new FileInputStream(Uri.parse(path)));
Hello I want to save captured photo in application directory where SQLite etc reside. I don't want to make any folder and any hidden file in the SD Card. How this can be save the captured photo in application directory.
I am trying this below but it is saving in the SD card that is hidden file but I don't want this approach.
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
String capturedPhotoName = "." + System.currentTimeMillis() + ".png";
File photo = new File(Environment.getExternalStorageDirectory(),
capturedPhotoName);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
startActivityForResult(cameraIntent, CAMERA_INTENT_REQUEST);
Thanks in advance !
Try this method to save captured image in application storage
public Uri setImageUri() {
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
File file = new File(directory,System.currentTimeMillis() + ".png");
Uri imgUri = Uri.fromFile(file);
this.imgPath = file.getAbsolutePath();
return imgUri;
}
Image will store at this location
/data/data/com.your.packagename/app_data/imageDir
get URI from onActivityResult() and convert it into bytes store bytes in Database.
byte[] UserPic = null;
UserPic = Base64.decode(result.getData(), 0);
save userPic in DataBase
I want to make a picture with the camera intent and save it to the default DCIM folder. Then I want to get the path/filename where the picture is stored.
I am trying it with the following code:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, TAKE_PICTURE);
With this code, the camera opens and after I have taken one picture it closes and saves the picture to the default image folder (usually /dcim/camera or sdcard/dcim/camera...)
but how can I get the path and filename of the taken picture now?
I have tried almost everything in onActivityResult
I tried
String result = data.getData();
and
String result = data.getDataString();
and
String result = data.toURI();
and
Uri uri = data.getData();
etc.
I researched the last two days to find a solution for this, there are many articles on the web and on stackoverflow but nothing works.
I don't want a thumbnail, I only want the path (uri?) to the image that the camera has taken.
Thank you for any help
EDIT:
When I try:
path=Environment.DIRECTORY_DCIM + "/test.jpg";
File file = new File(path);
Uri outputFileUri = Uri.fromFile(file);
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, TAKE_PICTURE);
it does not store the image as test.jpg but with the normal image name 2011-10-03.....jpg (but that is ok too, i only need the path to the image, it does not matter what the name is).
Best regards
EDIT Again
path=Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/";
File file = new File(path,"test111111111.jpg");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
Uri outputFileUri = Uri.fromFile(file);
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, TAKE_PICTURE);
When I try this, it stores the image to the right folder and with the given name (e.g. test111111.jpg).
But how can I get the filepath now in onActivityResult?
The picture will be stored twice, first on gallery folder, and after on the file you especified on putExtra(MediaStore.EXTRA_OUTPUT, path) method.
You can obtain the last picture taken doing that:
/**
* Gets the last image id from the media store
* #return
*/
private int getLastImageId(){
final String[] imageColumns = { MediaStore.Images.Media._ID, MediaStore.Images.Media.DATA };
final String imageOrderBy = MediaStore.Images.Media._ID+" DESC";
Cursor imageCursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageColumns, null, null, imageOrderBy);
if(imageCursor.moveToFirst()){
int id = imageCursor.getInt(imageCursor.getColumnIndex(MediaStore.Images.Media._ID));
String fullPath = imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
Log.d(TAG, "getLastImageId::id " + id);
Log.d(TAG, "getLastImageId::path " + fullPath);
imageCursor.close();
return id;
}else{
return 0;
}
}
This sample was based on post: Deleting a gallery image after camera intent photo taken
you can use like this in onActivityResult()
if(requestCode==CAMERA_CAPTURE)
{
Cursor cursor = getContentResolver().query(Media.EXTERNAL_CONTENT_URI, new String[]{Media.DATA, Media.DATE_ADDED, MediaStore.Images.ImageColumns.ORIENTATION}, Media.DATE_ADDED, null, "date_added ASC");
if(cursor != null && cursor.moveToFirst())
{
do
{
String picturePath =cursor.getString(cursor.getColumnIndex(Media.DATA));
Uri selectedImage = Uri.parse(picturePath);
}
while(cursor.moveToNext());
cursor.close();
File out = new File(picturePath);
try
{
mOriginal = decodeFile(out);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
mSelected.setImageBitmap(mOriginal);
}
}
When you are starting the ACTION_IMAGE_CAPTURE you can pass an extra MediaStore.EXTRA_OUTPUT as the URI of the file where you want to save the picture.
Here is a simple example:
File file = new File(path);
Uri outputFileUri = Uri.fromFile(file);
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, TAKE_PICTURE);
EDIT: I just tried on my device and file.createNewFile() solved the problem for me.