Skip to content

Instantly share code, notes, and snippets.

@remylavergne
Created March 4, 2020 12:59
Show Gist options
  • Save remylavergne/ef7e3407f0561670d925d62bbd629419 to your computer and use it in GitHub Desktop.
Save remylavergne/ef7e3407f0561670d925d62bbd629419 to your computer and use it in GitHub Desktop.
[Android] Utils

Bitmap to Byte Array

    suspend fun bitmapToByteArray() = withContext(Dispatchers.Default) {
        val stream = ByteArrayOutputStream()
        imageSelected?.compress(Bitmap.CompressFormat.PNG, 100, stream)
        imageSelectedByteArray = stream.toByteArray()
    }

Get Bitmap from Uri

fun getBitmapFromUri(context: Context, uri: Uri) {
        imageSelected = when {
            Build.VERSION.SDK_INT < 28 -> {
                MediaStore.Images.Media.getBitmap(context.contentResolver, uri)
            }
            Build.VERSION.SDK_INT >= 28 -> {
                val source = ImageDecoder.createSource(context.contentResolver, uri)
                ImageDecoder.decodeBitmap(source)
            }
            else -> {
                throw Exception("SDK version unknown :|")
            }
        }
    }

Persist Bitmap to Local Storage

private suspend fun persistBitmapToInternalStorage(context: Context, image: Bitmap): File? {
        return withContext(Dispatchers.Default) {
            val contextWrapper = ContextWrapper(context)
            val screenshotDirectory =
                contextWrapper.getDir(SCREENSHOT_LOCAL_DIR, Context.MODE_PRIVATE)
            val screenshotFile = File(screenshotDirectory, "${System.currentTimeMillis()}.jpg")
            if (!screenshotFile.exists()) {
                try {
                    val fos = FileOutputStream(screenshotFile)
                    image.compress(Bitmap.CompressFormat.JPEG, 80, fos)
                    fos.flush()
                    fos.close()
                    return@withContext screenshotFile
                } catch (e: Exception) {
                    Crash.log(
                        this::class,
                        "Error while transform Bitmap to persistent file on local storage",
                        e
                    )
                    return@withContext null
                }
            } else {
                Crash.log(
                    this::class,
                    "The filename already exist in local storage => Barely impossible, because name is generated from actual timestamp millis"
                )
                return@withContext screenshotFile
            }
        }
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment