Skip to content

Instantly share code, notes, and snippets.

@gpetuhov
Created September 19, 2019 13:38
Show Gist options
  • Save gpetuhov/807b99039d3d6a6920284e2995e363db to your computer and use it in GitHub Desktop.
Save gpetuhov/807b99039d3d6a6920284e2995e363db to your computer and use it in GitHub Desktop.
Android save image into gallery
// Android save image into gallery
private fun saveImage(image: File) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
saveImageWithMediaStore(image)
} else {
saveImageDirectly(image)
}
}
private fun saveImageWithMediaStore(image: File) {
val values = contentValues().apply {
put(MediaStore.Images.Media.RELATIVE_PATH, Constants.Image.IMAGE_FOLDER_NAME)
put(MediaStore.Images.Media.IS_PENDING, true)
// RELATIVE_PATH and IS_PENDING are introduced in API 29.
}
val resolver = context.contentResolver
val uri: Uri? = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
if (uri != null) {
val outputStream = resolver.openOutputStream(uri, "w")
if (outputStream != null) {
val inputStream = FileInputStream(image)
inputStream.copyTo(outputStream)
values.put(MediaStore.Images.Media.IS_PENDING, false)
context.contentResolver.update(uri, values, null, null)
}
}
}
private fun saveImageDirectly(image: File) {
val directory = File(Environment.getExternalStorageDirectory().toString() + "/" + Constants.Image.IMAGE_FOLDER_NAME)
// getExternalStorageDirectory is deprecated in API 29
if (!directory.exists()) {
directory.mkdirs()
}
val timeStamp = getCurrentTimeString()
val fileName = "$timeStamp.jpg"
val file = File(directory, fileName)
val inputStream = FileInputStream(image)
val outputStream = FileOutputStream(file)
inputStream.copyTo(outputStream)
val values = contentValues()
values.put(MediaStore.Images.Media.DATA, file.absolutePath)
// .DATA is deprecated in API 29
context.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
}
private fun getCurrentTimeString() = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
private fun contentValues() : ContentValues {
return ContentValues().apply {
put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis() / 1000)
put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment