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.
Related
I'm trying to save bitmap to gallery to open it again from ImagePicker intent.
The problem is - if I'm saving it on external storage, it will not work on devices without it, and when I'm writing it on internal storage - it won't shown in gallery, so i can not pick that image.
Tried so many ways of resolving it, but no success this far.
I mean, is it possible to save bitmap in internal storage and open it from activity, which called to choose image from gallery?
edit: added code
private String saveToInternalStorage(Bitmap bitmapImage, String filename){
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
// Create imageDir
File mypath=new File(directory,filename + ".jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return directory.getAbsolutePath();
}
With that procedure it's seems like saving bitmap is ok, but i can't find that file in gallery.
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.
I am developing an application for Android, and part of the application has to takes pictures and save them to the SDcard. The onPictureTaken method returned a byte array with the data of the captured image.
All I need to do is save the byte array into a .jpeg image file. I have attempted to do this with the help of BitmapFactory.decodeByteArray (to get a Bitmap) and then bImage.compress (to an OutputStream), a plain OutputStream, and a BufferedOutputStream. All three of these methods seem to give me the same weird bug. My Android phone (8MP camera and a decent processor), seems to save the photo (size looks correct), but in a corrupted way (the image is sliced and each slice is shifted; or I just get almost horizontal lines of various colors); and The weird thing is, that an Android tablet with a 5MP camera and a fast processor, seems to save the image correctly.
So I thought maybe the processor can't keep up with saving large images, because I got OutOfMemory Exceptions after about 3 pictures (even at compression quality of 40). But then how does the built in Camera app do it, and much faster too? I'm pretty sure (from debug) that the OutputStream writes all the data (bytes) and it should be fine, but it's still corrupted.
***In short, what is the best/fastest way (that works) to save a byte array to a jpeg file?
Thanks in advance,
Mark
code I've tried (and some other slight variations):
try {
Bitmap image = BitmapFactory.decodeByteArray(args, 0, args.length);
OutputStream fOut = new FileOutputStream(externalStorageFile);
long time = System.currentTimeMillis();
image.compress(Bitmap.CompressFormat.JPEG,
jpegQuality, fOut);
System.out.println(System.currentTimeMillis() - time);
fOut.flush();
fOut.close();
} catch (Exception e) {
}
and
try {
externalStorageFile.createNewFile();
FileOutputStream fos = new FileOutputStream(externalStorageFile);
fos.write(args);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
All I need to do is save the byte array into a .jpeg image file.
Just write it out to a file. It already is in JPEG format. Here is a sample application demonstrating this. Here is the key piece of code:
class SavePhotoTask extends AsyncTask<byte[], String, String> {
#Override
protected String doInBackground(byte[]... jpeg) {
File photo=new File(Environment.getExternalStorageDirectory(), "photo.jpg");
if (photo.exists()) {
photo.delete();
}
try {
FileOutputStream fos=new FileOutputStream(photo.getPath());
fos.write(jpeg[0]);
fos.close();
}
catch (java.io.IOException e) {
Log.e("PictureDemo", "Exception in photoCallback", e);
}
return(null);
}
}
Hey this codes for kotlin
camera.addCameraListener(object : CameraListener(){
override fun onPictureTaken(result: PictureResult) {
val jpeg = result.data //result.data is a ByteArray!
val photo = File(Environment.getExternalStorageDirectory(), "/DCIM/androidify.jpg");
if (photo.exists()) {
photo.delete();
}
try {
val fos = FileOutputStream(photo.getPath() );
fos.write(jpeg);
fos.close();
}
catch (e: IOException) {
Log.e("PictureDemo", "Exception in photoCallback", e)
}
}
})
This Code is perfect for saving image in storage, from byte[]...
note that "image" here is byte[]....taken as "byte[] image" as a parameter into a function.
File photo=new File(Environment.getExternalStorageDirectory(), "photo.jpg");
if (photo.exists()) {
photo.delete();
}
try {
FileOutputStream fos=new FileOutputStream(photo.getPath());
Toast.makeText(this, photo.getPath(), Toast.LENGTH_SHORT).show();
fos.write(image);
fos.close();
}
catch (java.io.IOException e) {
Log.e("PictureDemo", "Exception in photoCallback", e);
}
}
Here's the function to convert byte[] into image.jpg
public void SavePhotoTask(byte [] jpeg){
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "Life Lapse");
imagesFolder.mkdirs();
final File photo= new File(imagesFolder, "name.jpg");
try
{
FileOutputStream fos=new FileOutputStream(photo.getPath());
fos.write(jpeg);
fos.close();
}
catch(Exception e)
{
}
}
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 web service that returns a jpg. I read this jpg into a byte[], convert to a Bitmap, and save it to the SD card. The next time the user comes to this Activity, it will search the SD card to see if the image exists before hitting the web service.
However, the code that checks the SD card returns a StreamCorruptedException if the file exists.
Here is my code that writes to the SD card:
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
String root = Environment.getExternalStorageDirectory().toString();
new File(root + "/images").mkdirs();
try {
File file = new File(root + "/images", Integer.toString(intImageId) + "m.jpg");
FileOutputStream os = new FileOutputStream(file);
Bitmap theImageFromByteArray = BitmapFactory.decodeByteArray(image, 0, image.length);
theImageFromByteArray.compress(Bitmap.CompressFormat.JPEG, 80, os);
os.flush();
os.close();
}
catch (FileNotFoundException e) {
}
catch (IOException e) {
}
}
Here is my code that checks the SD card for the existing image:
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
|| Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
try {
File file = new File(Environment.getExternalStorageDirectory() + "/images", Integer.toString(mImageId) + "m.jpg");
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
mImage = (Bitmap)ois.readObject();
ois.close();
}
catch (Exception e) {
}
}
The exception happens during new ObjectInputStream(fis)
You cannot arbitrarily readObject() like this. writeObject() needs to be used in order for readObject() to detect a valid serialized object.