Question

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...

Was it helpful?

Solution

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.

OTHER TIPS

Although the selected answer is correct but for those who are looking for Kotlin code. Here I have already written a detailed article on the topic for both Java and Kotlin. Convert Bitmap to File in Android.

fun bitmapToFile(bitmap: Bitmap, fileNameToSave: String): File? { // File name like "image.png"
        //create a file to write bitmap data
        var file: File? = null
        return try {
            file = File(Environment.getExternalStorageDirectory().toString() + File.separator + fileNameToSave)
            file.createNewFile()

            //Convert bitmap to byte array
            val bos = ByteArrayOutputStream()
            bitmap.compress(Bitmap.CompressFormat.PNG, 0, bos) // YOU can also save it in JPEG
            val bitmapdata = bos.toByteArray()

            //write the bytes in file
            val fos = FileOutputStream(file)
            fos.write(bitmapdata)
            fos.flush()
            fos.close()
            file
        } catch (e: Exception) {
            e.printStackTrace()
            file // it will return null
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top