0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Kotlinで撮った画像を圧縮する

Posted at

スマホで撮影した画像はサイズが大きく、そのまま扱うとアップロードの時に時間がかかったり、アップロードできなかったりします。なのでKotlinで画像を圧縮する方法をメモします。

Bitmap.compress() を利用すれば、簡単に画像を圧縮してファイルに保存できます。
qualityを値で画像をどの程度圧縮させるか決めます。圧縮させすぎると画像が潰れてしまうので、注意します。

button?.setOnClickListener {
    val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
    imagePickerLauncher.launch(intent)
}

private val imagePickerLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
    if (result.resultCode == Activity.RESULT_OK) {
        val imageUri: Uri? = result.data?.data
        compressImage(this, it, 70)?.let { file ->
            Log.d("compressImage", "ファイルパス: ${file.absolutePath}")
        }
    }
}


private fun compressImage(context: Context, imageUri: Uri, quality: Int = 80): File? {
    return try {
        val inputStream = context.contentResolver.openInputStream(imageUri)
        val bitmap = BitmapFactory.decodeStream(inputStream)
        inputStream?.close()

        val outputFile = File(context.cacheDir, "compressed_image.jpg")
        val outputStream = FileOutputStream(outputFile)

        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream)
        outputStream.flush()
        outputStream.close()

        outputFile
    } catch (e: Exception) {
        e.printStackTrace()
        null
    }
}
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?