How to store bitmap in sdcard android example

Create a bitmap from a drawable resource image in the following way .BitmapFactory creates Bitmap objects from various sources, including files, streams, and byte-arrays. Here we are creating bitmap from a drawable image.

Bitmap bmap = BitmapFactory.decodeResource(context.getResources(),R.drawable.img);

//getExternalStorageDirectory() gets the android external storage directory which is later use to create a file .

File sdCardDirectory = Environment.getExternalStorageDirectory();

//  file for image storage

File image_file = new File(sdCardDirectory, "result.png");

//changing image format as png and FileOutputStream  writesbytes to a file

FileOut putStream outStream;

try {

// the outStream writes to file image_file

outStream = new FileOutputStream(image_file);

// compresses bmap and store it in the file using outstream

bmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);

// 100 to keep full quality of the image

outStream.flush();//Flushes the outStream stream

outStream.close();//Closes this stream.

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

Remember , you need to add the following permission in the manifest file :

 <uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE”/>

Advertisements