Exporting Bitmap to Image Folder in Android

Public on July 13, 2009
Say you have a bitmap (dynamically created or what) and you want to save that bitmap to the image folder of the external sdcard. you could do something like this. For better result you could use Threads to preform this operation.

String filename = String.valueOf(System.currentTimeMillis()) ;
ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, filename);
values.put(Images.Media.DATE_ADDED, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/jpeg");

Uri uri = context.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
try {
  OutputStream outStream = context.getContentResolver().openOutputStream(uri);
  mBitmap.compress(Bitmap.CompressFormat.JPEG, 90, outStream);
  outStream.flush();
  outStream.close();
  Log.d("done","done");
} catch (FileNotFoundException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
}




Explanation
First we create the current time as the filename of our new image
String filename = String.valueOf(System.currentTimeMillis()) ;

Create a ContentValue and put the fields needed to insert a new image to our Image Database
ContentValues values = new ContentValues();
......


Tell the Image Database on which type are we going to save, you can change this to image/png if you need the alphas
values.put(Images.Media.MIME_TYPE, "image/jpeg");

Add the new record to our image Database
Uri uri = context.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);

Open an output stream of our bitmap on the URI that is returned after we inserted a new record
OutputStream outStream = context.getContentResolver().openOutputStream(uri);

Using our bitmap (mBitmap), output the bitmap with the compression and quality to the output stream
mBitmap.compress(Bitmap.CompressFormat.JPEG, 90, outStream);

Flush and close the stream
outStream.flush();
outStream.close();


Hope this helps


Reference
http://www.developer.com/java/j2me/article.php/3748281

Update History
   Jan 17, 2012 - Visual Update




[Advertising]Faster Thinking - Speed up your brain


Faster Thinking Game



sentiment_satisfied Emoticon