Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 773
Krunal Panchal Avatar asked Apr 01 '14 11:04

Krunal Panchal


2 Answers

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.

like image 183
Saran Avatar answered Nov 05 '22 06:11

Saran


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
        }
    }
like image 41
Asad Ali Choudhry Avatar answered Nov 05 '22 04:11

Asad Ali Choudhry