Saving and Reading Bitmaps/Images from Internal memory in Android

前端 未结 7 1363
傲寒
傲寒 2020-11-22 02:59

What I want to do, is to save an image to the internal memory of the phone (Not The SD Card).

How can I do it?

I have got the image directly

7条回答
  •  醉酒成梦
    2020-11-22 03:15

    if you want to follow Android 10 practices to write in storage, check here and if you only want the images to be app specific, here for example if you want to store an image just to be used by your app:

    viewModelScope.launch(Dispatchers.IO) {
                getApplication().openFileOutput(filename, Context.MODE_PRIVATE).use {
                    bitmap.compress(Bitmap.CompressFormat.PNG, 50, it)
                }
            }
    

    getApplication is a method to give you context for ViewModel and it's part of AndroidViewModel later if you want to read it:

    viewModelScope.launch(Dispatchers.IO) {
                val savedBitmap = BitmapFactory.decodeStream(
                    getApplication().openFileInput(filename).readBytes().inputStream()
                )
            }
    

提交回复
热议问题