150

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?

Mxyk
  • 10,678
  • 16
  • 57
  • 76

6 Answers6

271

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();
Teo Inke
  • 5,928
  • 4
  • 38
  • 37
amsiddh
  • 3,513
  • 2
  • 24
  • 27
  • 40
    don't forget to flush and close your output stream :) – Ben Holland Oct 14 '12 at 03:38
  • 4
    Code works fine,but compress method takes lot of time. Any work around? – Shail Adi Apr 04 '13 at 09:34
  • 10
    incase people are wondering what Quality metric is. It is scale of 0 low to 100, high similar to photoshop export etc. As mentioned, its ignored for PNG, but you might wish to use `CompressFormat.JPEG`. As per google doco: *Hint to the compressor, 0-100. 0 meaning compress for small size, 100 meaning compress for max quality. Some formats, like PNG which is lossless, will ignore the quality setting* – wired00 Sep 23 '13 at 06:28
  • 3
    Will the file from the cache directory will be deleted automatically? – Shajeel Afzal Aug 01 '15 at 09:40
  • What is the advantage to buffering the bytes in memory prior to writing to storage? – Mark Apr 05 '16 at 23:21
  • 1
    Why use a `ByteArrayOutputStream`, get a byte array from that, then write the array to a `FileOutputStream`? Why not just the `FileOutputStream` in `Bitmap.compress`? – InsanityOnABun Sep 12 '17 at 03:34
  • what is bitmap.compress? why this function give PNG format? and what is 0? – roghayeh hosseini Feb 04 '19 at 17:57
94

Try this:

bitmap.compress(Bitmap.CompressFormat.PNG, quality, outStream);

See this

gprathour
  • 14,813
  • 5
  • 66
  • 90
P.Melch
  • 8,066
  • 43
  • 40
  • 14
    But I don't want a `FileOutputStream`, just a File. Is there a way around this? – Mxyk Oct 14 '11 at 15:51
  • 1
    A FileOutputStream is how you write to a file. See http://developer.android.com/reference/java/io/FileOutputStream.html – Torid Oct 14 '11 at 17:08
  • i don't really know what you mean... You use a FileOutputStream to create a file. And you can use a File instance ( like in the example of amsiddh) to create a FileOutputStream that you can export the bitmap to. With that ( a File instance, an actual file on the filesystem and the FileOutputStream ) you should have everything you need, no? – P.Melch Oct 17 '11 at 18:48
  • Quality is an int from 0 to 100 inclusive, specifying quality (`Hint to the compressor`, so its not necessarily a rule it follows). https://developer.android.com/reference/android/graphics/Bitmap#compress(android.graphics.Bitmap.CompressFormat,%20int,%20java.io.OutputStream) – Ben Butterworth Dec 12 '20 at 01:05
49
File file = new File("path");
OutputStream os = new BufferedOutputStream(new FileOutputStream(file));
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
os.close();
fraggjkee
  • 3,524
  • 2
  • 32
  • 38
14

Converting Bitmap to File needs to be done in background (NOT IN THE MAIN THREAD) it hangs the UI specially if the bitmap was large

File file;

public class fileFromBitmap extends AsyncTask<Void, Integer, String> {

    Context context;
    Bitmap bitmap;
    String path_external = Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg";

    public fileFromBitmap(Bitmap bitmap, Context context) {
        this.bitmap = bitmap;
        this.context= context;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // before executing doInBackground
        // update your UI
        // exp; make progressbar visible
    }

    @Override
    protected String doInBackground(Void... params) {

        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        file = new File(Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg");
        try {
            FileOutputStream fo = new FileOutputStream(file);
            fo.write(bytes.toByteArray());
            fo.flush();
            fo.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }


    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        // back to main thread after finishing doInBackground
        // update your UI or take action after
        // exp; make progressbar gone

         sendFile(file);

    }
}

Calling it

new fileFromBitmap(my_bitmap, getApplicationContext()).execute();

you MUST use the file in onPostExecute .

To change directory of file to be stored in cache replace line :

 file = new File(Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg");

with :

file  = new File(context.getCacheDir(), "temporary_file.jpg");
Mohamed Embaby
  • 960
  • 8
  • 26
  • 1
    This gives me "FileNotFound" exception some times. I am still investigating why this happens. Also maybe you should consider saving the wile with .webp extension its around 40-50% lesser size than JPG – Pranaysharma Mar 05 '18 at 15:26
  • I suppose "FileNotFound" exception happens when save to cache then somehow cache is cleared(there many ways to get cache cleared, maybe by another application) @Pranaysharma – Mohamed Embaby Mar 05 '18 at 15:43
  • Isn't missing the execute() after the constructor : new fileFromBitmap(my_bitmap, getApplicationContext()); ? – Andrea Leganza Oct 10 '18 at 12:49
  • 1
    @AndreaLeganza yes it was missing, I edited my answer, thanks to you. – Mohamed Embaby Oct 10 '18 at 13:57
  • Keeping the Contex in AsyncTask may lead to memory leaks!!! https://www.youtube.com/watch?v=bNM_3YkK2Ws – slaviboy Jun 03 '20 at 14:52
9

Most of the answers are too lengthy or too short not fulfilling the purpose. For those how are looking for Java or Kotlin code to Convert bitmap to File Object. Here is the detailed article I have written on the topic. Convert Bitmap to File in Android

public static File bitmapToFile(Context context,Bitmap bitmap, String fileNameToSave) { // File name like "image.png"
        //create a file to write bitmap data
        File file = null;
        try {
            file = new File(Environment.getExternalStorageDirectory() + File.separator + fileNameToSave);
            file.createNewFile();

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

//write the bytes in file
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(bitmapdata);
            fos.flush();
            fos.close();
            return file;
        }catch (Exception e){
            e.printStackTrace();
            return file; // it will return null
        }
    }
Asad Ali Choudhry
  • 4,985
  • 4
  • 31
  • 36
3

Hope this helps u

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    // Get the bitmap from assets and display into image view
    val bitmap = assetsToBitmap("tulip.jpg")
    // If bitmap is not null
    bitmap?.let {
        image_view_bitmap.setImageBitmap(bitmap)
    }


    // Click listener for button widget
    button.setOnClickListener{
        if(bitmap!=null){
            // Save the bitmap to a file and display it into image view
            val uri = bitmapToFile(bitmap)
            image_view_file.setImageURI(uri)

            // Display the saved bitmap's uri in text view
            text_view.text = uri.toString()

            // Show a toast message
            toast("Bitmap saved in a file.")
        }else{
            toast("bitmap not found.")
        }
    }
}


// Method to get a bitmap from assets
private fun assetsToBitmap(fileName:String):Bitmap?{
    return try{
        val stream = assets.open(fileName)
        BitmapFactory.decodeStream(stream)
    }catch (e:IOException){
        e.printStackTrace()
        null
    }
}


// Method to save an bitmap to a file
private fun bitmapToFile(bitmap:Bitmap): Uri {
    // Get the context wrapper
    val wrapper = ContextWrapper(applicationContext)

    // Initialize a new file instance to save bitmap object
    var file = wrapper.getDir("Images",Context.MODE_PRIVATE)
    file = File(file,"${UUID.randomUUID()}.jpg")

    try{
        // Compress the bitmap and save in jpg format
        val stream:OutputStream = FileOutputStream(file)
        bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream)
        stream.flush()
        stream.close()
    }catch (e:IOException){
        e.printStackTrace()
    }

    // Return the saved bitmap uri
    return Uri.parse(file.absolutePath)
}

}

brkcnplt
  • 57
  • 6