Skip to content

Instantly share code, notes, and snippets.

@Razeeman
Created July 31, 2019 08:06
Show Gist options
  • Save Razeeman/bbe1b369e4d528137cceefaeb1062357 to your computer and use it in GitHub Desktop.
Save Razeeman/bbe1b369e4d528137cceefaeb1062357 to your computer and use it in GitHub Desktop.
File Uri and Content Uri from Bitmap
class FileUtils {
companion object {
private const val FILENAME = "temp_bitmap"
@JvmStatic
fun getFileUriFromBitmap(context: Context, bitmap: Bitmap): Uri {
val file = getFileFromBitmap(context, bitmap)
return Uri.parse(file.toURI().toString())
}
@JvmStatic
fun getContentUriFromBitmap(context: Context, bitmap: Bitmap): Uri {
val file = getFileFromBitmap(context, bitmap)
val providerName = "${context.applicationContext.packageName}.provider"
return FileProvider.getUriForFile(context, providerName, file)
}
@SuppressLint("SetWorldReadable")
private fun getFileFromBitmap(context: Context, bitmap: Bitmap): File {
val file = File(context.cacheDir, "$FILENAME.png")
val fos = FileOutputStream(file)
fos.use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos) }
file.setReadable(true, false)
return file
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment