Skip to content

Instantly share code, notes, and snippets.

@imandaliya
Created August 9, 2021 10:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imandaliya/7c80bb3330e77245e77154a62480a164 to your computer and use it in GitHub Desktop.
Save imandaliya/7c80bb3330e77245e77154a62480a164 to your computer and use it in GitHub Desktop.
private fun saveImageToStorage() {
try {
val uri: Uri?
val fileName = "Screenshot_${Calendar.getInstance().time}.jpg"
val imageOutStream: OutputStream? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val values = ContentValues()
values.put(MediaStore.Images.Media.DISPLAY_NAME, fileName)
values.put(MediaStore.Images.Media.MIME_TYPE, "image/*")
values.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES)
uri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
uri?.let { contentResolver.openOutputStream(it) }
} else {
val imagesDir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), getString(R.string.app_name))
imagesDir.mkdirs()
val imagePath = File(imagesDir, fileName)
uri = Uri.fromFile(imagePath)
FileOutputStream(imagePath)
}
imageOutStream.use { outStream ->
getViewScreenshot(imageView).compress(Bitmap.CompressFormat.JPEG, 100, outStream)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment