3

I want to convert a bitmap object to a file object. However, I want to store the file object on memory, not in SDcard or internal storage, so that I can use the image file without saving in gallery.

The code below is just for acquiring the bitmap and converting it into smaller image

 public void onActivityResult(int requestCode, int resultCode, Intent data){
    super.onActivityResult(requestCode, resultCode, data);

    if(resultCode != RESULT_OK)
        return;

    if(requestCode == PICK_FROM_CAMERA){

        imageUri = data.getData();



        Cursor c = this.getContentResolver().query(imageUri, null, null, null, null);
        c.moveToNext();
        absolutePath = c.getString(c.getColumnIndex(MediaStore.MediaColumns.DATA));

        Glide.with(this).load(imageUri).into(image);


        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 4;
        bitmap = BitmapFactory.decodeFile(absolutePath, options);



    }
심희수
  • 123
  • 1
  • 2
  • 5

2 Answers2

21

Hope this will help you

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);
  }
}
Akash
  • 961
  • 6
  • 15
3

For those how are looking for 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

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
        }
    }
Asad Ali Choudhry
  • 4,985
  • 4
  • 31
  • 36