i wanted to add file with specific path like that to view it as in image .. worked fine
File imgFile = new File("/storage/emulated/0/DSC_0008.JPG");
if (imgFile.exists()) {
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imageView);
myImage.setImageBitmap(myBitmap);
BUT
that is not where i find my photo .. if i tried opening it manually and not from the studio
any idea how this work .. and how do i know the path that should i use to get any photo on my android
The "/storage/emulated/0/" folder does not really exist.
It's what might be called a "symbolic link", or, in simpler terms, a reference to where the real data is stored. You'll need to find the actual physical location on your device where it is stored.
Since it's in /storage/emulated/0/DSC_0008.JPG, it's probably located in /Internal Storage/DSC_0008.JPG/. Please note that that this folder probably only contains "DSC_0008.JPG", which are very small versions of the real files.
It's possible your real files are gone forever if your SD card is irrecoverable.
As Hiren stated, you'll need a file explorer to see your directory. If you're rooted I highly suggest root explorer, otherwise ES File Explorer is a good choice.
You can user file chooser for get image path
private void chooserImage(){
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 1888);
}
Then override a method called onActivityResult
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == getActivity().RESULT_OK && requestCode==1888){
Uri imageUri = data.getData();
String path = imageUri.getPath().toString();
File imgFile = new File(new URI(path));
//Then Here user your code
if (imgFile.exists()) {
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imageView);
myImage.setImageBitmap(myBitmap);
}
}
}
Just Call on any event chooserImage(); to choose file and show as ImageView
You need one more step: set permission to read SD card. Add this in AndroidManifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Judging by the filename, DSC_0008.JPG, I'm assuming it was made with the Camera app. If that's the case your file should be in /sdcard/DCIM/Camera/
try this
File imgFile = getOutputFile("myfileName", "imagesSubFolder");
public static File getOutputFile(String fileName, String subFolderName) {
File mediaStorageDir;
if (subFolderName == null) {
mediaStorageDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), Path.PHOTO_DIRECTORY);
} else {
mediaStorageDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), Path.PHOTO_DIRECTORY + File.separator + subFolderName);
}
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
return null;
}
} else {
try {
if (subFolderName != null) {
File noMediaFile = new File(mediaStorageDir, ".nomedia");
noMediaFile.createNewFile();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return new File(mediaStorageDir.getPath() + File.separator + fileName);
}
good luck
Related
I can save the captured image to Pictures folder however i cannot save it to app folder. I give permissions for camera and write permission dynamically. I write read write camera permission in manifests.xml. I checked permission at debug mode. There is no problem with permissions.
Camera activity starts and i take picture and click OK. Then in onActivityResult() i checked the image file's size.It's zero byte. Image file exists but zero length.
Here is how i retrieve image path :
public static File getImageFile(Context context, int food_id) {
try {
//File storageDir = new File(context.getFilesDir().getAbsolutePath() + File.separator + IMAGES_DIRECTORY); // not works !!!!!!!!!
File storageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString() + File.separator + IMAGES_DIRECTORY); // works
if (!storageDir.exists()) {
storageDir.mkdirs();
}
File photoFile = new File(storageDir.getAbsolutePath() + File.separator + food_id + ".jpg");
/* if(!photoFile.exists())
photoFile.createNewFile();*/
return photoFile;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
if (Build.VERSION.SDK_INT >= 23) {
hasPermissionCamera = ContextCompat.checkSelfPermission(FoodDetailsActivity.this, Manifest.permission.CAMERA);
if (hasPermissionCamera != PackageManager.PERMISSION_GRANTED) {
if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) {
getErrorDialog(getString(R.string.permission_error_dialog_camera), FoodDetailsActivity.this, true).show();
} else {
requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_CODE_ASK_PERMISSIONS_CAMERA);
}
} else { // open camera
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) // intent düzgün mü diye kontrol eder.
{
File photoFile = AppUtil.getImageFile(FoodDetailsActivity.this,food_id);
if (photoFile != null) {
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
}
} else {
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intentx) {
super.onActivityResult(requestCode, resultCode, intentx);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
File imageFile = AppUtil.getImageFile(this,food_id);
try {
mImageBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath()); // mImageBitmap is null here. imageFile exists.
Log.d("eeffs","size : " + imageFile.length() + " - exists() : " + imageFile.exists()); exists return true. length is zero
int widthBitmap = mImageBitmap.getWidth(); // exception here because bitmap is null
...
} catch (IOException e) {
e.printStackTrace();
}
}
}
i cannot save it to app folder
I am going to guess that you mean:
File storageDir = new File(context.getFilesDir().getAbsolutePath() + File.separator + IMAGES_DIRECTORY); // not works !!!!!!!!!
Third party apps have no ability to write to your app's portion of internal storage, and you are invoking a third-party camera app via ACTION_IMAGE_CAPTURE.
You can use FileProvider and its getUriForFile() method to provide selective access to your app's portion of internal storage. This sample app demonstrates the technique, where I also write to a location inside of getFilesDir().
As a bonus, using FileProvider will allow you to get rid of that ugly StrictMode hack that you are using to try to get past the ban on file Uri schemes.
Sorry to bother you guys, but I am not able to get a solution where In we take picture using intents. I know the default behavior of native camera is to save the picture at default directory/place of O.S. The thing is I have some requirements where I do not want to save the picture when clicked using camera app. There has to be a solution of this issue, be it like once we take a picture we could delete it right away, or there should be an alternate by which we won't allow O.S to save Image, please help.
Here is a piece of code I tried, tried several ways by creating a directory and then deleting file, nothing works.
public void takeImageFromCamera() {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check for the integer request code originally supplied to startResolutionForResult().
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
if (isCameraPermissionGranted()) {
bitmap= (Bitmap) data.getExtras().get("data");
// bitmap = processReuiredImage(picUri);
getProfileDetailViaFace(encodeImageBitmapToString(bitmap));
Log.d("path",String.valueOf(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES)));
// getApplicationContext().getContentResolver().delete(, "/storage/emulated/0/Pictures", null);
// mediaStorageDir.getPath().delete();
} else {
requestCameraPermission();
}
}
public void takeImageFromCamera() {
File file = getOutputMediaFile(CAMERA_FILE_TYPE);
if (Build.VERSION.SDK_INT >= 24) {
try {
Method m = StrictMode.class.getMethod("disableDeathOnFileUriExposure");
m.invoke(null);
} catch (Exception e) {
e.printStackTrace();
}
}
picUri = Uri.fromFile(file);
Intent takePictureIntent = new
Intent(MediaStore.ACTION_IMAGE_CAPTURE_SECURE);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, picUri);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, CAMERA_REQUEST);
}
}
private File getOutputMediaFile(int type) {
mediaStorageDir = new
File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "peppercard");
/**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());
if (type == CAMERA_FILE_TYPE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_" + timeStamp + ".jpeg");
} else {
return null;
}
}
return mediaFile;
}
The thing is I have some requirements where I do not want to save the picture when clicked using camera app
The decision of whether or not to save an image is up to the camera app, not you. There are hundreds of camera apps that might respond to ACTION_IMAGE_CAPTURE, and the developers of those apps can do whatever they want.
There has to be a solution of this issue, be it like once we take a picture we could delete it right away, or there should be an alternate by which we won't allow O.S to save Image,
Take the photo yourself, using the camera APIs or libraries that wrap around them (e.g., CameraKit-Android, Fotoapparat).
There has to be a solution of this issue, be it like once we take
a picture we could delete it right away
Indeed there is. You could specify a path (even using a file provider) where the camera app has to put the image in a file.
Then when the camera app is done you can get the image from that file and then delete the file.
Have a look at Intent.EXTRA_OUTPUT.
Pretty standard your question. You can find a lot of example code on this site.
Final I have found the answer after waiting from past 2 days, yay..It will not save the file as I am just deleting the file after returning from the activity.
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null, null, null)
int column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToLast();
String imagePath = cursor.getString(column_index_data);
Bitmap bitmapImage = BitmapFactory.decodeFile(imagePath );
Log.d("bitmapImage", bitmapImage.toString()); /*delete file after taking picture*/
Log.d("imagePath", imagePath.toString());
File f = new File(imagePath);
if (f.exists()){
f.delete();
}
sendBroadcast(newIntent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,Uri.fromFile(f)));
thank you for your appreciation in advance.
I am coding in next contidion.
a. use internal camera app(I use Intent and other app to take pickture).
b. get image without saving into file.
In my app, user take pickture of a credit card and send to server. Credit card image file is not necessary and saving image into file is not good for security.
Is it possible?
If it is impossible, is there anything else?
a. opening jpg file, editing all pixel into black
b. use https://github.com/Morxander/ZeroFill
Whitch method is properable?
Short answer is NO.
You can't get an photo from default camera app without saving it into image.
What you can do is use Camera API to take photo inside your app, not using 3rd party default system photo app.
Look here full Source.
Request this permission on the AndroidManifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
On your Activity, start by defining this:
static final int REQUEST_IMAGE_CAPTURE = 1;
private Bitmap mImageBitmap;
private String mCurrentPhotoPath;
private ImageView mImageView;
Then fire this Intent in an onClick:
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Log.i(TAG, "IOException");
}
// Continue only if the File was successfully created
if (photoFile != null) {
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
}
}
Add the following support method:
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, // prefix
".jpg", // suffix
storageDir // directory
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
Then receive the result:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
try {
mImageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath));
mImageView.setImageBitmap(mImageBitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
What made it work is the MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath)), which is different from the code from developer.android.com. The original code gave me a FileNotFoundException.
I tried to take a picture using camera intent and want to get the file path of the full size image. I am following the tutorial from http://developer.android.com/training/camera/photobasics.html. The problem, when I look into the file path in MediaStore.Images.Media.DATA column using MediaStore.Images.Media.EXTERNAL_CONTENT_URI, the image have different path. How do I supply the same file path? I looked at taking a photo and placing it in the Gallery, I though it is simply just change Environment.DIRECTORY_PICTURES to Environment.DIRECTORY_DCIM, but it still didn't work.
Below is my code for taking photo.
private Uri photoPath;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_IMAGE_CAPTURE) {
getContentResolver().notifyChange(photoPath, null);
System.out.println(photoPath);
}
}
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.camera_button) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
try {
String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String image = "IMG_" + timestamp;
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File photo = File.createTempFile(image, ".jpg", storageDir);
photoPath = Uri.fromFile(photo);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoPath);
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
}
}
my code above produce file path /storage/emulated/0/Pictures/IMG_20150805_121624.jpg while it is actually /storage/emulated/0/DCIM/100MEDIA/IMAG0531.jpg in the gallery. the former path is really my image (as I specified it on photoPath), but I want to get the later path instead. How could I do that?
You will have to use Environment.DIRECTORY_DCIM.
The android API DOC clearly has the details of various directories which can be used.
I hope this will help you to save your file to /storage/emulated/0/DCIM/.
I can press a button, open up the native camera app, and successfully take a picture. But then when I check the Gallery or Photos native apps on my phone, the picture isn't saved there. I'm very new to Android so it's likely I'm missing something important in my code.
Questions:
1) Where are these pictures being saved?
2) Can I modify the below code somehow to save instead to internal storage, so all pictures taken with my app are private and only accessible through my app?
3) If I wanted to save these pictures to an object, along with some text/other input, what would be the best way? Should I just save a Uri or some identifier to reference the image later, or save the actual BitMap image?
Any help is greatly appreciated, thanks!
Here is my code to take the picture:
mImageButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
imageUri = CameraUtils.getOutputMediaFileUri(CameraUtils.MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, REQUEST_IMAGE);
}
}
CameraUtils class taken straight from Google developer guides:
public static Uri getOutputMediaFileUri(int type)
{
return Uri.fromFile(getOutputMediaFile(type));
}
public static File getOutputMediaFile(int type)
{
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "camera");
if (!mediaStorageDir.exists())
{
if (!mediaStorageDir.mkdirs())
{
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE)
{
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_" + timeStamp + ".jpg");
}
else if(type == MEDIA_TYPE_VIDEO)
{
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_" + timeStamp + ".mp4");
}
else
{
return null;
}
return mediaFile;
}
1) By looking at the code, I'd expect the pictures to be saved in a directory called 'camera' which would be found in the Pictures folder on your device (external storage). These might not instantly appear in your gallery, however in later versions of Android (Kitkat and maybe jelly-bean though I can't verify that right now) you should be able to open the Photos app and find them somewhere in there. If that is not the case, then launch a file explorer app (example apps are ASTRO File Manager or X-Plore) and browse to the Pictures/camera directory where you should see your images. The next time your media gets re-indexed (phone reboot, or a re-index triggered from elsewhere), you should see these pictures in your gallery/photo apps. If you want to refresh your media programatically, here might help. Finally, make sure you have the READ_EXTERNAL_STORAGE permission in your Android manifest as specified this (Android doc).
2) If you want to save images to be only available to your application, you need to save them to your application's internal data directory. Take a look at this straight from the Android doc. Make sure to use the MODE_PRIVATE flag.
3) For this, you would want to store the file path somewhere accessible to your app. Either you could save your file paths to a text file with some other text data, or you could use a sqlite database. Finally, you could use an ORM like ORMLite for Android to save a java object which might hold data for your picture and have some fields you want to persist (title, description, path, etc). Here and here is an intro on how to get started with SQLite database in Android (straight from the official doc). If you want to use ORMLite, there is plenty of information on their site here. The developer has spent a lot of time answering StackOverflow questions..
All of your questions can be answered with a few simple Google searches. They are very standard and basic things to do in Android, so you should be able to find a plethora of information and tutorials online.
EDIT:
In response to your comment about the second question. This is what I would probably do (or something similar):
Note that I didn't test this. It's from the top of my head. If you have more issues comment here!
Activity code...
mImageButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
imageUri = CameraUtils.getOutputMediaFileUri(currentActivity, CameraUtils.MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, REQUEST_IMAGE);
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == REQUEST_IMAGE)
{
if (resultCode == RESULT_OK)
{
String pathToInternallyStoredImage = CameraUtils.saveToInternalStorage(this, imageUri);
// Load the bitmap from the path and display it somewhere, or whatever
}
else if (resultCode == RESULT_CANCELED)
{
//Cancel code
}
}
}
CameraUtils class code...
public static Uri getOutputMediaFileUri(int type)
{
return Uri.fromFile(getOutputMediaFile(type));
}
public static File getOutputMediaFile(int type)
{
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "camera");
createMediaStorageDir(mediaStorageDir);
return createFile(type, mediaStorageDir);
}
private static File getOutputInternalMediaFile(Context context, int type)
{
File mediaStorageDir = new File(context.getFilesDir(), "myInternalPicturesDir");
createMediaStorageDir(mediaStorageDir);
return createFile(type, mediaStorageDir);
}
private static void createMediaStorageDir(File mediaStorageDir) // Used to be 'private void ...'
{
if (!mediaStorageDir.exists())
{
mediaStorageDir.mkdirs(); // Used to be 'mediaStorage.mkdirs();'
}
} // Was flipped the other way
private static File createFile(int type, File mediaStorageDir ) // Used to be 'private File ...'
{
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile = null;
if (type == MEDIA_TYPE_IMAGE)
{
mediaFile = new File(mediaStorageDir .getPath() + File.separator +
"IMG_" + timeStamp + ".jpg");
}
else if(type == MEDIA_TYPE_VIDEO)
{
mediaFile = new File(mediaStorageDir .getPath() + File.separator +
"VID_" + timeStamp + ".mp4");
}
return mediaFile;
}
public static String saveToInternalStorage(Context context, Uri tempUri)
{
InputStream in = null;
OutputStream out = null;
File sourceExternalImageFile = new File(tempUri.getPath());
File destinationInternalImageFile = new File(getOutputInternalMediaFile(context).getPath());
try
{
destinationInternalImageFile.createNewFile();
in = new FileInputStream(sourceExternalImageFile);
out = new FileOutputStream(destinationInternalImageFile);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0)
{
out.write(buf, 0, len);
}
}
catch (IOException e)
{
e.printStackTrace();
//Handle error
}
finally
{
try {
if (in != null) {
in.close();
}
if (out != null) {
in.close();
}
} catch (IOException e) {
// Eh
}
}
return destinationInternalImageFile.getPath();
}
So now you have the path pointing to your internally stored image, which you can then manipulate/load from your onActivityResult.