Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save siscofran999/0ae39382e7e657b8fd8542bdd7d62dbf to your computer and use it in GitHub Desktop.
Save siscofran999/0ae39382e7e657b8fd8542bdd7d62dbf to your computer and use it in GitHub Desktop.
saveImage
@Throws(IOException::class)
fun saveImage(context: Context, bitmap: Bitmap, folderName: String, fileName: String): Uri? {
val fos: OutputStream?
var imageFile: File? = null
var imageUri: Uri? = null
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val resolver = context.contentResolver
val contentValues = ContentValues()
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg")
contentValues.put(
MediaStore.MediaColumns.RELATIVE_PATH,
Environment.DIRECTORY_DCIM + File.separator + folderName
)
imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
fos = resolver.openOutputStream(imageUri!!)
} else {
val imagesDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM
).toString() + File.separator + folderName
imageFile = File(imagesDir)
if (!imageFile.exists()) {
imageFile.mkdir()
}
imageFile = File(imagesDir, "$fileName.jpeg")
fos = FileOutputStream(imageFile)
}
bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos)
fos?.flush()
fos?.close()
if (imageFile != null) // pre Q
{
MediaScannerConnection.scanFile(context, arrayOf(imageFile.toString()), null, null)
imageUri = Uri.fromFile(imageFile)
}
return imageUri
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment