convert android.graphics.Bitmap to java.io.File

Krunal Panchal picture Krunal Panchal · Apr 1, 2014 · Viewed 20.4k times · Source

I want to upload edited Bitmap image to server using multipart uploading like this,

multipartEntity.addPart("ProfilePic", new FileBody(file));

But I can't convert Bitmap(android.graphics.Bitmap) image to File(java.io.File).

I tried to convert it to byte array but It also didn't worked.

Does anybody know inbuilt function of android or any solution to convert Bitmap to File?

Please help...

Answer

Saran picture Saran · Apr 1, 2014

This should do it:

private static void persistImage(Bitmap bitmap, String name) {
  File filesDir = getAppContext().getFilesDir();
  File imageFile = new File(filesDir, name + ".jpg");

  OutputStream os;
  try {
    os = new FileOutputStream(imageFile);
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
    os.flush();
    os.close();
  } catch (Exception e) {
    Log.e(getClass().getSimpleName(), "Error writing bitmap", e);
  }
}

Change the Bitmap.CompressFormat and extension to suit your purpose.