Skip to content

Instantly share code, notes, and snippets.

@dmersiyanov
Created May 31, 2022 07:58
Show Gist options
  • Save dmersiyanov/d878968317ca59e4b15d0bbd7c4abfea to your computer and use it in GitHub Desktop.
Save dmersiyanov/d878968317ca59e4b15d0bbd7c4abfea to your computer and use it in GitHub Desktop.
Save bitmap to external storage android
import android.content.ContentValues
import android.graphics.Bitmap
import android.os.Build
import android.provider.MediaStore
import androidx.fragment.app.Fragment
import timber.log.Timber
import java.io.IOException
/**
* Check for right mediaUri depend on [Build.VERSION.SDK_INT]
* On sdk < Build.VERSION_CODES.Q permission [android.Manifest.permission.WRITE_EXTERNAL_STORAGE]
* need to ne requested before calling this function
* */
fun Fragment.saveBitmapToStorage(bitmap: Bitmap) {
val filename = "${System.currentTimeMillis()}.jpg"
val mediaUri =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
MediaStore.Images.Media.getContentUri(
MediaStore.VOLUME_EXTERNAL_PRIMARY
)
} else {
MediaStore.Images.Media.EXTERNAL_CONTENT_URI
}
requireActivity().applicationContext?.contentResolver?.also { resolver ->
val contentValues = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, filename)
put(MediaStore.MediaColumns.MIME_TYPE, "image/jpg")
put(MediaStore.MediaColumns.WIDTH, bitmap.width)
put(MediaStore.MediaColumns.HEIGHT, bitmap.height)
}
runCatching {
resolver.insert(mediaUri, contentValues)?.let { imageUri ->
resolver.openOutputStream(imageUri)?.use { stream ->
if (!bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream)) {
throw IOException("Cannot save image")
}
}
}
}.onSuccess {
// success
}.onFailure {
Timber.e(it)
// error
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment