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

I want to upload the edited Bitmap image to the server using multi-page download, e.g.

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

But I can not convert the Bitmap ( android.graphics.Bitmap) to File ( java.io.File).

I tried converting it to an array of bytes, but it also did not work.

Does anyone know the built-in android function or any solution to convert Bitmap to file?

Please, help...

+4
source share
1 answer

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);
  }
}

Modify Bitmap.CompressFormatand expand according to your tasks.

+24
source

Source: https://habr.com/ru/post/1534426/


All Articles