やりたいこと
サーバーに渡せるようにUriからbyteArrayに変換してMultiPartBodyにする前準備をしておきたい
コード
decoder.kt
val imageStream: InputStream? = context.contentResolver.openInputStream(imageUri)
val bitmap = BitmapFactory.decodeStream(imageStream)
val byteArrayOutputStream = ByteArrayOutputStream()
val compressFormat = when (mimeType) {
MediaType.Jpeg -> {
Bitmap.CompressFormat.JPEG
}
MediaType.Png -> {
Bitmap.CompressFormat.PNG
}
else -> {
throw IllegalStateException("media type not found")
}
}
bitmap.compress(compressFormat, 100, byteArrayOutputStream)
byteArrayOutputStream.toByteArray()
MediaTypeは個別で用意しているenum classになっており、MediaTypeによりBitmap作成時のFormatが変わります
予期しないMediaTypeが帰ってきた場合、IllegalStateExceptionが帰ってくるようにしています
bitmap.compress()の引数は(Bitmap.CompressFormat,Int, OutputStream)
となっておりフォーマット方法、クオリティ、ByteArrayOutputStreamが実体となっています