Convert Bitmap to File

Mxyk picture Mxyk · Oct 14, 2011 · Viewed 174.8k times · Source

I understand that using BitmapFactory can convert a File to a Bitmap, but is there any way to convert a Bitmap image to a File?

Answer

amsiddh picture amsiddh · Oct 15, 2011

Hope it will help u:

//create a file to write bitmap data
File f = new File(context.getCacheDir(), filename);
f.createNewFile();

//Convert bitmap to byte array
Bitmap bitmap = your bitmap;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();

//write the bytes in file
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();