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.
Related
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);
I can pass sdcard location to my adb command using
file:///sdcard/Android/screen.bmp
What is the equivalent string, if my file is saved in phone memory instead of sdcard, will it be
file:///phone/Android/screen.bmp
That isn't necessarily how you access things saved internally on your phone.
Keep in mind how you save an image to internal storage:
Bitmap bitmap = ______; //get your bitmap however
try {
FileOutputStream fos = context.openFileOutput("desiredFilename.png", Context.MODE_PRIVATE);
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
} catch (Exception e) {
Log.e("saveToInternalStorage()", e.getMessage());
Log.e("Saving the bitmap",e.getMessage());
}
Now, to go read it, we just get the context, and call getFileStreamPath(filename) on it.
Bitmap retrievedImage;
String filename = "desiredFilename.png";
try {
File filePath = context.getFileStreamPath(filename);
FileInputStream fi = new FileInputStream(filePath);
retrievedImage = BitmapFactory.decodeStream(fi);
} catch (Exception e) {
Log.e("Retrieving the image", e.getMessage());
}
You can read more about this here.
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();
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.
I have a set of image urls. I download it to bitmap. Now I want to store these images into sdcard/project folder. If I don't have such a file, I have to create it. What I have done right now is:
String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
File file = new File(path, imageName);
if(!file.exists()) {
file.mkdir();
try {
fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.flush();
fOut.close();
MediaStore.Images.Media.insertImage(getContentResolver(), "file://"
+ file.getAbsolutePath(), file.getName(), file.getName());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
But I am not getting images inserted into sdcard. What is wrong in my code? Please reply. Thanks in advance.
Try using the below code:
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
String fileName = edtNameImage.getText().toString().trim();//this can be changed
if (fileName.equalsIgnoreCase("")) {
Toast.makeText(context, "Fields cannot be left blank",
Toast.LENGTH_SHORT).show();
return false;
}
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + fileName);
// write the bytes in file
FileOutputStream fo;
try {
file.createNewFile();
fo = new FileOutputStream(file);//snapshot image is the image to be stored.
if (snapShotImage!=null)
{
snapShotImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
}else{
return false;
}
fo.write(bytes.toByteArray());
// ChartConstants.IMAGE_STORAGE++;
fo.flush();
fo.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return true;
You can also check for duplicacy in names with some additional code lines.
Let me know if it helps.
Have you made sure that the appropriate permissions for writing to/reading from an external storage device have been set in your Manifest.xml file?
Also, does the code exit with any of the exceptions above? Print more illustrative messages than the stacktrace. Something like so:
try {
} catch (FileNotFoundException e) {
Log.v(this.toString(), "Exception caught in block");
}
or something on these lines..
HTH
Sriram
Problems with your code:
1) You are creating a directory with the filename. Instead try mkdir() with only the 'path'
2) Pass only 'file.getAbsolutePath()' without the "file://" to insertImage() function
3) There is an alternate api to insertImage for which you need not create one more file locally. Pass the bitmap directly to that.
Hope this helps.