Created
June 21, 2021 03:47
-
-
Save siscofran999/0ae39382e7e657b8fd8542bdd7d62dbf to your computer and use it in GitHub Desktop.
saveImage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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