where/how to store an image private to my app? (Android) - android

I've got a image selector/cropper with code taken from this site
They create the image in the phone's external storage but I want to store this in my app's internal storage, a process documented here
This is what my function to retrieve the temp file looks like, however when I try to use the file returned from this function, the image does not change. In fact, looking at logcat, it seems resolveUri failed on bad bitmap uri on that file I generated. The error occurs when I try to set the Image URI, leading me to believe it was not saved properly. This is odd to me considering the original code from the site just creates a file in the SD card, and the code works fine for reading/writing to that. So I wonder where the problem arises.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PHOTO_PICKED:
if (resultCode == RESULT_OK) {
if (data != null) {
Bundle extras = data.getExtras();
if (extras != null) {
ImageView callerImage = (ImageView)findViewById(R.id.contact_image);
callerImage.setImageURI(Uri.fromFile(getTempFile()));
}
}
}
break;
}
}
private File getTempFile() {
try {
FileOutputStream fos = openFileOutput(TEMP_PHOTO_FILE, Context.MODE_WORLD_WRITEABLE);
fos.close();
File f = getFileStreamPath(TEMP_PHOTO_FILE);
return f;
} catch (FileNotFoundException e) {
// To be logged later
return null;
} catch (IOException e) {
// To be logged later
return null;
}
}

Never mind, I am so silly. When I called getTempFile, each time it recreates the file, which is a mistake. It should only create the file on the initial call and simply open it the rest of the time.

Related

Picture Intent Zero Length Image

What am I doing wrong here? I'm trying to call the intent to get a picture in full size:
takePictureIntent
private void takePictureIntent(int request) {
final Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(activity.getPackageManager()) != null) {
File file = null;
try {
file = createImageFile(request);
} catch (Exception e) {
showErrorDialog(getString(R.string.error), getString(R.string.error_saving_picture));
Log.e(TAG, "Error while creating image file.");
}
if (file != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(takePictureIntent, request);
} else {
Log.e(TAG, "Error while creating image file.");
showErrorDialog(getString(R.string.error), getString(R.string.error_saving_picture));
}
}
}
createImageFile
private File createImageFile(final int request) {
final File storageDir = new File(activity.getExternalFilesDir(Environment.DIRECTORY_PICTURES), getString(R.string.app_name));
if (!storageDir.exists()) {
if (!storageDir.mkdirs()) {
Log.e(TAG, "Cannot create parent folders.");
return null;
}
}
File file = null;
try {
file = File.createTempFile("test_", ".jpg", storageDir);
} catch (Exception e) {
Log.e(TAG, "Error while creating temp file.");
}
fileProduct = file;
return file;
}
onActivityResult
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_IMAGE_PRODUCT) {
if (fileProduct == null ||!fileProduct.exists() ||fileProduct.length() == 0) {
showErrorDialog(getString(R.string.error), getString(R.string.error_taking_product_picture));
return;
}
}
Sometimes (yes, sometimes) the length of the resulting file is 0. I know for sure that the folders in private app context exist and the image files as well (with length > 0). Could you please provide some help? I'm on 6.0 on Nexus 5X.
I would start by getting rid of File.createTempFile(). You do not need it, it wastes time, and it might cause some camera apps to want to not store the photo in that file (since the file is already there). Just generate a unique filename yourself. This will incrementally help with your compatibility.
Also, you need to make sure that you are holding onto fileProduct in the saved instance state Bundle, as your app's process may be terminated while the camera app is in the foreground.
However, in general, ACTION_IMAGE_CAPTURE is not very reliable. You are delegating the work to one of hundreds of possible camera apps, and some of those apps have bugs. One such bug is ignoring EXTRA_OUTPUT. So, in onActivityResult(), if you determine that you have a valid fileProduct value, but there is no file there, call data.getData() and see if you have a Uri there. In that case, the camera app may have stored the photo at the location identified by that Uri, and you can use ContentResolver and DocumentFile to try to work with that Uri.
Using this:
final String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
file = new File(storageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
instead of
File.createTempFile()
magically seems to fix the problem. Thanks to CommonsWare for (somehow) pointing me in the right direction.

Android image captured stored into server is rotated when retrieved

In my code I allow user to upload photos from gallery or from camera. Then image is stored into the server through retrofit. When retrieved the photo is always rotated 90 degrees if the photo is taken using the phone's camera (regardless whether it is from invoked through the app or invoked through the camera directly). If the images are not taken using the camera, the orientation is correct. How do I resolve this?
I know if I tried to display the image directly without storing it in server, and it was possible to be in the right orientation because I could rotate it before displaying. I am doing something similar to the codes here: https://gist.github.com/Mariovc/f06e70ebe8ca52fbbbe2.
But because I need to upload to the server and then retrieve from the server again. How do I rotate it before storing to the server so that when I retrieve it, it is already in the right orientation?
Below is some parts of my codes (just some usual handling of images and displayAvatarInProfile() is called after the service finished the downloading of image):
public void displayAvatarInProfile(String filePath) {
if(filePath != null && filePath != ""){
int targetW = mProfilePicImageView.getWidth();
int targetH = mProfilePicImageView.getHeight();
Bitmap bm = ImageStorageUtils.resizePic(filePath, targetW, targetH);
mProfilePicImageView.setImageBitmap(bm);
} else {
mProfilePicImageView.setImageBitmap(null);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == Activity.RESULT_OK) {
Uri fileUri = null;
String filePath = null;
switch(requestCode) {
case REQUEST_PICK_IMAGE:
fileUri = data.getData();
break;
case REQUEST_CAPTURE_IMAGE:
File imageFile = ImageStorageUtils.getFile(
getActivity().getResources().getString(R.string.ApptTitle),
"avatar_" + mUser.getLogin());
filePath = imageFile.getAbsolutePath();
fileUri = ImageStorageUtils.getUriFromFilePath(mContext.get(), filePath);
break;
default:
break;
}
if(fileUri != null) {
getActivity().startService(ProfileService.makeIntentUploadAvatar(
mContext.get(), mUser.getId(), fileUri));
}
}
}
public void pickImage() {
final Intent imageGalleryIntent =
new Intent(Intent.ACTION_PICK, Media.EXTERNAL_CONTENT_URI)
.setType("image/*")
.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
// Verify the intent will resolve to an Activity.
if (imageGalleryIntent.resolveActivity(getActivity().getPackageManager()) != null)
// Start an Activity to get the Image from the Image Gallery
startActivityForResult(imageGalleryIntent,
DisplayProfileFragment.REQUEST_PICK_IMAGE);
}
public void captureImage() {
Uri captureImageUri = null;
try {
captureImageUri = Uri.fromFile(ImageStorageUtils.createImageFile(
mContext.get(),
getActivity().getResources().getString(R.string.ApptTitle),
"avatar_" + mUser.getLogin()));
} catch (IOException e) {
e.printStackTrace();
}
// Create an intent that will start an Activity to get
// capture an image.
final Intent captureImageIntent =
new Intent(MediaStore.ACTION_IMAGE_CAPTURE)
.putExtra(MediaStore.EXTRA_OUTPUT, captureImageUri);
// Verify the intent will resolve to an Activity.
if (captureImageIntent.resolveActivity(getActivity().getPackageManager()) != null)
// Start an Activity to capture an image
startActivityForResult(captureImageIntent,
DisplayProfileFragment.REQUEST_CAPTURE_IMAGE);
}
Update 1
Was commented that I needed more description:
When I am uploading a file, I do this:
boolean succeeded = mImpatientServiceProxy.uploadAvatar(userId, new TypedFile("image/jpg", imageFile));
When I download, I get a retrofit.client.Response object, which I then get the InputStream from the Response and write the data to a file using an Output Stream.
final InputStream inputStream = response.getBody().in();
final OutputStream outputStream = new FileOutputStream(file);
IOUtils.copy(inputStream, outputStream);
Update 2
This is not a duplicate of existing solution because the user can upload from gallery, you do not know if it is a photo taken from resources online or from camera, so you cannot rotate the image when you display it.
Use camera api instead of intent. When you capture image using intents it displays rotated. In camera api there are methods by which you can change the rotation of the camera as well as the captured photo too.

Android Unable to get path for Cloud image from Photos Application

I have tried to getting absolute path and I got the success too but when I try with the cloud images to get that image and used in application file is not find and getting null. I am implementing to receive files from another app like when you select image from Photos, Gallery or File application and share image by using my application.
Here I got the Uri content://com.google.android.apps.photos.contentprovider/0/1/mediaKey%3A%2FAF1QipOFLMMm8uXbeDMQk-P4S0Hx1dlmRDMr4SFABfVi/ACTUAL/61235243
When I select image which is on Google Photos cloud and it'll be first download and then given me above URI. From that point I directly execute in query and getting the name of the file "Filename.png" in all the columns but not the full path.
When same things I tried with the Facebook to share it will display in compose exact which I want to share.
I have also refer this from this link to get the path from Photos application, but the problem is with cloud image.
Anybody have solution or suggestion will be appriciated.
Try getting the Bitmap first:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Uri selectedImage = data.getData();
InputStream inputStreamBitmap = null;
Bitmap imageBitmap = null;
try {
inputStreamBitmap = getContentResolver().openInputStream(inputStreamBitmap);
imageBitmap = BitmapFactory.decodeStream(inputBitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (inputStreamBitmap != null) {
inputStreamBitmap.close();
}
} catch (IOException ignored) {
}
}
if (imageBitmap != null) {
processImageBitmap(imageBitmap);
} else {
Log.e("ImageIntent", "Error: couldn't open the specified image.");
}
}
}
Then you could save the Bitmap to a temp file if you want to.
More details here.

Bitmap of size zero saved from Camera App on cancel

I was following the android tutorial as follows from this official link
I wish to save the full Image. The problem is when the user enters the camera app takes a photo but decides to cancel it, android still saves the image with size zero. Any way to avoid this?
The code is as follows
static final int REQUEST_TAKE_PHOTO = 1;
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
File 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) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
Ok solved it using the name of the newly created file. When we create name of file we simply save the path of the file in a String variable say "Current Path"
And add the following code-
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == Activity.RESULT_CANCELED && requestCode == 0)
{
File file = new File(currentPath);
boolean delete = file.delete();
Log.i("delete",String.valueOf(delete));
}
}
I think you are doing something wrong in your code. You should post your code to get the proper assistance.
as far as I understand . You should override the onbackpressed function. you should close/release camera here. In this case I think the camera would not take and save picture.

Trouble writing internal memory android

void launchImageCapture(Activity context) {
Uri imageFileUri = context.getContentResolver()
.insert(Media.INTERNAL_CONTENT_URI, new ContentValues());
m_queue.add(imageFileUri);
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageFileUri);
context.startActivityForResult(i, ImportActivity.CAMERA_REQUEST);
}
The above code, which has always worked, is now generating this exception for me at insert().
java.lang.UnsupportedOperationException: Writing to internal storage is not supported.
at com.android.providers.media.MediaProvider.generateFileName(MediaProvider.java:2336)
at com.android.providers.media.MediaProvider.ensureFile(MediaProvider.java:1851)
at com.android.providers.media.MediaProvider.insertInternal(MediaProvider.java:2006)
at com.android.providers.media.MediaProvider.insert(MediaProvider.java:1974)
at android.content.ContentProvider$Transport.insert(ContentProvider.java:150)
at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:140)
at android.os.Binder.execTransact(Binder.java:287)
at dalvik.system.NativeStart.run(Native Method)
It is not a space issue, and the only thing I changed was the package of an unrelated class all together. Also, I restarted my phone.
Facing same problem here, I was happy to find this thread. Even though two things were bugging me in this workaround, this post had me looking in the right direction. I'd like to share my own workaround/solution.
Let me begin by stating what I did not see myself living with.
First, I did not want to leave the application private file as MODE_WORLD_WRITEABLE. This looks like non-sense to me, although I cannot figure exactly how another application could access this file unless knowing where to look for it with complete name and path. I'm not saying it is necessarily bad for your scenario, but it is still bugging me somehow. I would prefer to cover all my bases by having picture files really private to my app. In my business case, pictures are of no use outside of the application and by no means should they be deleteable via, say, the Android Gallery. My app will trigger cleanup at an appropriate time so as to not vampirize Droid device storage space.
Second, openFileOutput() do not leave any option but to save the resulting file in the root of getFilesDir(). What if I need some directory structure to keep things in order? In addition, my application must handle more than one picture, so I would like to have the filename generated so I can refer to it later on.
See, it is easy to capture a photo with the camera and save it to public image area (via MediaStore) on the Droid device. It is also easy to manipulate (query, update, delete) media from MediaStore. Interestingly, inserting camera picture to MediaStore genreates a filename which appears to be unique. It is also easy to create private File for an application with a directory structure. The crux of the "Capturea camera picture and save it to internal memory" problem is that you can't do so directly because Android prevents ContentResolver to use Media.INTERNAL_CONTENT_URI, and because private app files are by definition not accessible via the (outside) Camera activity.
Finally I adopted the following strategy:
Start the Camera activity for result from my app with the Intent to capture image.
When returning to my app, insert capture to the MediaStore.
Query the MediaStore to obtain generated image file name.
Create a truly internal file onto whatever path relative to private application data folder using Context.getDir().
Use an OutputStream to write Bitmap data to this private file.
Delete capture from MediaStore.
(Optional) show an ImageView of the capture in my app.
Here is the code starting the cam:
public void onClick (View v)
{
ContentValues values = new ContentValues ();
values.put (Media.IS_PRIVATE, 1);
values.put (Media.TITLE, "Xenios Mobile Private Image");
values.put (Media.DESCRIPTION, "Classification Picture taken via Xenios Mobile.");
Uri picUri = getActivity ().getContentResolver ().insert (Media.EXTERNAL_CONTENT_URI, values);
//Keep a reference in app for now, we might need it later.
((XeniosMob) getActivity ().getApplication ()).setCamPicUri (picUri);
Intent takePicture = new Intent (MediaStore.ACTION_IMAGE_CAPTURE);
//May or may not be populated depending on devices.
takePicture.putExtra (MediaStore.EXTRA_OUTPUT, picUri);
getActivity ().startActivityForResult (takePicture, R.id.action_camera_start);
}
And here is my activity getting cam result:
#Override
protected void onActivityResult (int requestCode, int resultCode, Intent data)
{
super.onActivityResult (requestCode, resultCode, data);
if (requestCode == R.id.action_camera_start)
{
if (resultCode == RESULT_OK)
{
Bitmap pic = null;
Uri picUri = null;
//Some Droid devices (as mine: Acer 500 tablet) leave data Intent null.
if (data == null) {
picUri = ((XeniosMob) getApplication ()).getCamPicUri ();
} else
{
Bundle extras = data.getExtras ();
picUri = (Uri) extras.get (MediaStore.EXTRA_OUTPUT);
}
try
{
pic = Media.getBitmap (getContentResolver (), picUri);
} catch (FileNotFoundException ex)
{
Logger.getLogger (getClass ().getName ()).log (Level.SEVERE, null, ex);
} catch (IOException ex)
{
Logger.getLogger (getClass ().getName ()).log (Level.SEVERE, null, ex);
}
//Getting (creating it if necessary) a private directory named app_Pictures
//Using MODE_PRIVATE seems to prefix the directory name provided with "app_".
File dir = getDir (Environment.DIRECTORY_PICTURES, Context.MODE_PRIVATE);
//Query the MediaStore to retrieve generated filename for the capture.
Cursor query = getContentResolver ().query (
picUri,
new String [] {
Media.DISPLAY_NAME,
Media.TITLE
},
null, null, null
);
boolean gotOne = query.moveToFirst ();
File internalFile = null;
if (gotOne)
{
String dn = query.getString (query.getColumnIndexOrThrow (Media.DISPLAY_NAME));
String title = query.getString (query.getColumnIndexOrThrow (Media.TITLE));
query.close ();
//Generated name is a ".jpg" on my device (tablet Acer 500).
//I prefer to work with ".png".
internalFile = new File (dir, dn.subSequence (0, dn.lastIndexOf (".")).toString () + ".png");
internalFile.setReadable (true);
internalFile.setWritable (true);
internalFile.setExecutable (true);
try
{
internalFile.createNewFile ();
//Use an output stream to write picture data to internal file.
FileOutputStream fos = new FileOutputStream (internalFile);
BufferedOutputStream bos = new BufferedOutputStream (fos);
//Use lossless compression.
pic.compress (Bitmap.CompressFormat.PNG, 100, bos);
bos.flush ();
bos.close ();
} catch (FileNotFoundException ex)
{
Logger.getLogger (EvaluationActivity.class.getName()).log (Level.SEVERE, null, ex);
} catch (IOException ex)
{
Logger.getLogger (EvaluationActivity.class.getName()).log (Level.SEVERE, null, ex);
}
}
//Update picture Uri to that of internal file.
((XeniosMob) getApplication ()).setCamPicUri (Uri.fromFile (internalFile));
//Don't keep capture in public storage space (no Android Gallery use)
int delete = getContentResolver ().delete (picUri, null, null);
//rather just keep Uri references here
//visit.add (pic);
//Show the picture in app!
ViewGroup photoLayout = (ViewGroup) findViewById (R.id.layout_photo_area);
ImageView iv = new ImageView (photoLayout.getContext ());
iv.setImageBitmap (pic);
photoLayout.addView (iv, 120, 120);
}
else if (resultCode == RESULT_CANCELED)
{
Toast toast = Toast.makeText (this, "Picture capture has been cancelled.", Toast.LENGTH_LONG);
toast.show ();
}
}
}
Voila! Now we have a truly application private picture file, which name has been generated by the Droid device. And nothing is kept in the public storage area, thus preventing accidental picture manipulation.
here is my working code to save a captured image from the camera to app internal storage:
first, create the file with the desired filename. in this case it is "MyFile.jpg", then start the activity with the intent below. you're callback method(onActivityResult), will be called once complete. After onActivityResult has been called your image should be saved to internal storage. key note: the mode used in openFileOutput needs to be global.. Context.MODE_WORLD_WRITEABLE works fine, i have not tested other modes.
try {
FileOutputStream fos = openFileOutput("MyFile.jpg", Context.MODE_WORLD_WRITEABLE);
fos.close();
File f = new File(getFilesDir() + File.separator + "MyFile.jpg");
startActivityForResult(
new Intent(MediaStore.ACTION_IMAGE_CAPTURE)
.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f))
, IMAGE_CAPTURE_REQUEST_CODE);
}
catch(IOException e) {
}
and in the activity result method:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == IMAGE_CAPTURE_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
Log.i(TAG, "Image is saved.");
}
}
to retrieve your image:
try {
InputStream is = openFileInput("MyFile.jpg");
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 4;
Bitmap retrievedBitmap = BitmapFactory.decodeStream(is, null, options);
}
catch(IOException e) {
}
The camera apparently doesn't support writing to internal storage.
Unfortunately this is not mentioned in the documentation.
MediaProvider.java has the following code:
private String generateFileName(boolean internal,
String preferredExtension, String directoryName)
{
// create a random file
String name = String.valueOf(System.currentTimeMillis());
if (internal) {
throw new UnsupportedOperationException(
"Writing to internal storage is not supported.");
// return Environment.getDataDirectory()
// + "/" + directoryName + "/" + name + preferredExtension;
} else {
return Environment.getExternalStorageDirectory()
+ "/" + directoryName + "/" + name + preferredExtension;
}
}
So writing to internal storage has been intentionally disabled for the time being.
Edit - I think you can use binnyb's method as a work-around, but I wouldn't recommend it; I'm not sure if this will continue to work on future versions. I think the intention is to disallow writing to internal storage for media files.
I filed a bug in the Android issue tracker.
Edit - I now understand why binnyb's method works. The camera app is considered to be just another application. It can't write to internal storage if it doesn't have permissions. Setting your file to be world-writable gives other applications permission to write to that file.
I still don't think that this is a very good idea, however, for a few reasons:
You don't generally want other apps writing to your private storage.
Internal storage is quite limited on some phones, and raw camera images are quite large.
If you were planning on resizing the image anyway, then you can read it from external storage and write it yourself to your internal storage.

Categories

Resources