Android: Best way to save image at external Storage - android

When i'm trying to save an image at some devices the app crashes.
After some research i think the problem is the imageRoot, but i'm kind of lost with so many solutions...
I think the problem is about obtaining external storage path.
The device i'm using to test my app doesn't have any sd card, the path is /mnt/sdcard/Pictures and the image is being saved successfully.
I want it to work whether phone has an sd card or not.
Thanks for any help in advance.
imageRoot=new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "AppName");
private void saveImage() {
Bitmap bitmap = sqimage.getDrawingCache();
File image = new File(imageRoot, imageName);
if (image.exists()) {
image.delete();
}
try {
FileOutputStream output = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, output);
output.flush();
output.close();
new SingleMediaFileConnector(getActivity().getApplicationContext(), image);
} catch (FileNotFoundException e) {
e.printStackTrace();
success = false;
} catch (IOException e) {
e.printStackTrace();
success = false;
}
}

Sometimes getExternalStoragePublicDirectory path doesn't exist. You need to check for its existence.
try {
imageRoot=new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "AppName");
File image = new File(imageRoot, imageName);
// Make sure the Pictures directory exists.
imageRoot.mkdirs();
// Other stuffs here
} catch (IOException e) {
// Unable to create file, likely because external storage is
// not currently mounted.
Log.w("ExternalStorage", "Error writing " + file, e);
}
See here for more details.
[Edit]
An alternate way can be use:
getExternalFilesDir(Environment.DIRECTORY_PICTURES);

Related

Fastest way to save the image into SD card without using Async Task

I am using Async task for downloading some other data, while that Async task executes I want to save the image from the url into the SD card. So what can be the fastest way or any alternative to save the image into sd card without using Async task. I have searched on the Google and stackoverflow, but can't find the appropriate solution.
touchView.setDrawingCacheEnabled(true);
Bitmap bitmap = touchView.getDrawingCache();
File file = new File(Environment.getExternalStorageDirectory()
+ "/MultiTouchView_Image.png");
if (file.exists())
file.delete();
try {
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream ostream = new FileOutputStream(file);
bitmap.compress(CompressFormat.PNG, 10, ostream);
ostream.close();
touchView.invalidate();
} catch (Exception e) {
Log.e(TAG, "Save fail!");
e.printStackTrace();
} finally {
Log.e(TAG, "Save successfull!");
touchView.setDrawingCacheEnabled(false);
touchView.invalidate();
}
TouchView : The View you want to save to image.

Android Wear: how to store image data into watch

I'm looking for how to store image data into my app on Android Wear.
What I want to do are followings:
Take a photo and send it to my watch. (via DataMap)
My watch displays the photo.
When my app on Android Wear restarts, the app displays the photo taken before.
For now, the photo is cleared after restart the app. I want to store the photo.
Are there any ways to save the photo into the watch.
Thanks.
[UPDATE1]
I tried to save an image by using Environment.getExternalStorageDirectory()
But "NOT EXISTS" is returned.
String imagePath = Environment.getExternalStorageDirectory()+"/test.jpg";
try {
FileOutputStream out = openFileOutput(imagePath, Context.MODE_WORLD_READABLE);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
File file = new File(bitmapPath);
boolean isExists = file.exists();
if (isExists) {
LOGD(TAG, "EXISTS");
} else {
LOGD(TAG, "NOT EXISTS");
}
[UPDATE2]
I found an error below..
java.lang.IllegalArgumentException: File /storage/emulated/0/test.jpg contains a path separator
[UPDATE3]
try {
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(path));
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
java.io.FileNotFoundException: /image: open failed: EROFS (Read-only file system)
[UPDATE4]
I put it. But not change.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
[UPDATE5 SOLVED]
I found that the path "imagePath" was correct. (Sorry. I didn't notice it)
String imagePath = Environment.getExternalStorageDirectory() + "/test.jpg";
try {
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(imagePath));
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
I believe you are having problems because openFileInput() is for internal storage, not external storage. In fact there is no reason for using Environment.getExternalStorage(). I don't believe the watches have external storage anyway.
Try something like openFileOutput("test.jpg", Context.MODE_WORLD_READABLE); (fyi MODE_WORLD_READABLE is deprecated).
Then use openFileInput("test.jpg") to get it back.
The reason you are getting an error is openFileOutput() cannot have subdirectories.

Downloaded image shows in computer but not in mobiles folder

I am working on an image wallpaper application in android when i download the image from url sometime it shows images on mobile but most of time it does't show but when i connect my mobile to computer its right in the specified folder.
Thanks advance looking forward for answer.
Here is my code to download image.
protected Void doInBackground(Void... arg0) {
FileOutputStream fileOutput = null;
try {
// set the path where we want to save the file
// in this case, going to save it on the root directory of the
// sd card.
File dir = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
String filename = _imagePaths[FullScreenImage.position]
.substring(_imagePaths[FullScreenImage.position]
.lastIndexOf("/"));
if (!dir.exists())
dir.mkdirs();
File file = new File(dir, filename);
Log.i("Local filename:", "" + filename);
// this will be used to write the downloaded data into the file
// we created
fileOutput = new FileOutputStream(file);
Bitmap mybitmap = imageLoader.getBitmap(
_imagePaths[FullScreenImage.position], 800, 480);
mybitmap.compress(CompressFormat.JPEG, 100, fileOutput);
// close the output stream when done
// catch some possible errors...
} catch (IOException e) {
Log.e("Download Image catch > ", e.getMessage());
} finally {
if (fileOutput != null) {
try {
fileOutput.flush();
fileOutput.close();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("Download Image catch > ", e.getMessage());
}
}
}
return null;
}
Use MediaScannerConnection.scanFile() to notify the system about new media files.

Saved Bitmap doesn't appear on SD Card

I am working on an app in which I would like to save some Bitmaps to the SD Card. I have looked at a lot of examples and other questions, and from that I have made the following code:
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
String dirPath = Environment.getExternalStorageDirectory().toString() + "/myFolder";
File dir = new File(dirPath);
dir.mkdirs();
String fileName = "bitmapname.jpg";
File file = new File(dirPath, fileName);
FileOutputStream fileOutPutStream;
try {
boolean created = file.createNewFile();
Log.d("Checks", "File created: " + created);
fileOutPutStream = new FileOutputStream(file);
fileOutPutStream.write(byteArrayOutputStream.toByteArray());
fileOutPutStream.close();
} catch (FileNotFoundException e) {
Log.d("Checks", "FileNotFoundException");
e.printStackTrace();
} catch (IOException e) {
Log.d("Checks", "IOException");
Log.d("Checks", e.getMessage());
e.printStackTrace();
}
I don't see what's wrong with this code. It doesn't give any errors and my app runs without crashing. However, when I connect my phone to my computer and open the SD Card I do not see the folder "myFolder" and I can not find the saved image anywhere. Do you guys have any ideas as to why this is?
EDIT: I noticed that I can see the saved bitmaps in the Android gallery, and they are indeed in a folder called "myFolder". However, I still don't see them when I connect my phone to my computer and browse my sd card.
From my experience I had similar issued when I forgot the fileOutPutStream.flush(); before the close().
Are you sure you are setting the permission to write to SD card? Try setting this one:
WRITE_EXTERNAL_STORAGE
Edit:
Ok, try this:
Environment.getExternalStorageDirectory().getAbsolutePath()
Instead of:
Environment.getExternalStorageDirectory().toString()
Or even create a directory like this:
File dir = new File(Environment.getExternalStorageDirectory() +
File.separator +
"myFolder");
dir.mkdirs();

can't save file in android file system

I'm trying to capture a photo with the camera and save it (to be previewed later) and it seems to work with the emulator but when I use it on my GalaxyS - it doesn't save the file (I use RootExplorer to check) and there's no preview.
What am I doing wrong?
Code for saving the file:
public void onPictureTaken(byte[] data, Camera camera) {
FileOutputStream outStream = null;
try {
// Write to SD Card
String filename = "captured_image.jpg";
Log.d("##--File name--##", filename);
outStream = openFileOutput(filename, Context.MODE_WORLD_READABLE); // <9>
outStream.write(data);
outStream.close();
Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length);
} catch (FileNotFoundException e) { // <10>
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
Log.d(TAG, "onPictureTaken - jpeg");
}
Code for displaying:
ImageView imagePrev = (ImageView) findViewById(R.id.image_capturedimagepreview_preview);
Bitmap bmp = null;
try {
bmp = BitmapFactory.decodeStream(openFileInput("captured_image.jpg"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
imagePrev.setImageBitmap(bmp);
i think i found the problem.
instead of outStream = openFileOutput(filename, Context.MODE_WORLD_READABLE); i should use outStream = getApplicationContext().openFileOutput(filename, Context.MODE_WORLD_READABLE);
but now i'm facing a new one - the file seems to be corrupted cause when i open it with the Android's viewer it's just black and its size is always 18474 bytes.
any ideas?
Where are you storing the image? Have you tried using an absolute path? Do you have the read/write external permission in the manifest?
I used something like this in my program to store an image in a directory the same as my package name.
File path = new File(Environment.getExternalStorageDirectory(), context.getPackageName() );
File imagePath = new File(path,"capture_image.jpg");
EDIT:
If its your first time using the sd card for your given package name you will need to create the directory before trying to write to it.

Categories

Resources