LoginSignup
5
2

More than 5 years have passed since last update.

[Android][Kotlin]Base64をデコードして画像URIを作成する

Posted at

Base64でエンコードされた画像データを他アプリ等に共有できるようにURIを生成する方法です。

手順

  1. Base64をデコード
  2. Bitmap画像を作成
  3. URIを作成

Base64をデコード

画像データの場合、image/jpeg;base64,がBase64化した文字列の前についているので除外してデコードします。
jpegの部分は適宜 png等に変えてください。

val decodedBytes = Base64.decode(
  base64Str.substring(base64Str.indexOf(",") + 1),
  Base64.DEFAULT
)

Bitmap画像を作成

デコードしたデータからBitmap画像を作成します。
作成は BitmapFactorydecodeByteArrayを使用します。

BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.size)

URIを作成

作成したBitmap画像からURIを作成します。
ストレージに画像を保存するので、 AndroidManifestに android.permission.WRITE_EXTERNAL_STORAGEを追加しておきます。

val bytes = ByteArrayOutputStream()
bitmapImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes)
val path = MediaStore.Images.Media.insertImage(context.getContentResolver(), bitmapImage, "Title", null)
val uri = Uri.parse(path)

一度もストレージを使用したことがない場合、エラーが発生してしまうのでディレクトリの有無を確認してなければ作成しておきます。

val sdcard = Environment.getExternalStorageDirectory()
if (sdcard != null) {
  val mediaDir = File(sdcard, "DCIM/Camera")
  if (!mediaDir.exists()) {
    mediaDir.mkdirs()
  }
}

コード全文

以下に今回使用したコードを載せておきます。

// Base64 to Bitmap
@Throws(IllegalArgumentException::class)
fun convert(base64Str: String): Bitmap {
  val decodedBytes = Base64.decode(
    base64Str.substring(base64Str.indexOf(",") + 1),
    Base64.DEFAULT
  )

  return BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.size)
}

// Bitmap to URI
private fun getImageUri(context: Context, bitmapImage: Bitmap): Uri {
  val bytes = ByteArrayOutputStream()
  bitmapImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes)
  val sdcard = Environment.getExternalStorageDirectory()
  if (sdcard != null) {
    val mediaDir = File(sdcard, "DCIM/Camera")
    if (!mediaDir.exists()) {
      mediaDir.mkdirs()
    }
  }
  val path = MediaStore.Images.Media.insertImage(context.getContentResolver(), bitmapImage, "Title", null)
  return Uri.parse(path)
}

こんな感じで呼び出して使用して頂ければと思います。

val uri = getImageUri(applicationContext, convert(base64Str))
5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2