Android Studio: Save Image In Sd Card
I keep a school project dealing with a ListView filled with images hosted on a server. When someone selects an image from the list, this is shown by 'original' size in another layo
Solution 1:
First, you need to get your Bitmap. You can already have it as an object Bitmap, or you can try to get it from the ImageView such as:
BitmapDrawabledrawable= (BitmapDrawable) mImageView1.getDrawable();
Bitmapbitmap= drawable.getBitmap();
Then you must get to directory (a File object) from SD Card such as:
FilesdCardDirectory= Environment.getExternalStorageDirectory();
Next, create your specific file for image storage:
Fileimage=newFile(sdCardDirectory, "test.png");
After that, you just have to write the Bitmap thanks to its method compress such as:
booleansuccess=false;
// Encode the file as a PNG image.
FileOutputStream outStream;
try {
outStream = newFileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
/* 100 to keep full quality of the image */
outStream.flush();
outStream.close();
success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Finally, just deal with the boolean result if needed. Such as:
if (success) {
Toast.makeText(getApplicationContext(), "Image saved with success",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Error during image saving", Toast.LENGTH_LONG).show();
}
Don't forget to add the following permission in your Manifest:
<uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Solution 2:
It will be better to create a Dialog to let the user select where they want the photo to be store at. Remember there are a ton of android devices and they might vary.
Post a Comment for "Android Studio: Save Image In Sd Card"