-
Notifications
You must be signed in to change notification settings - Fork 0
GetImage
Dongwon Shin edited this page Jun 16, 2024
·
3 revisions
private fun requestCameraPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
requestPermissionLauncher.launch(Manifest.permission.CAMERA)
} else {
openCamera()
}
}
- 런타임에 카메라 권한을 요청합니다.
private val requestPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted: Boolean ->
if (isGranted) { openCamera() }
else {
Toast.makeText(this, "카메라 권한이 필요합니다.", Toast.LENGTH_SHORT).show()
}
}
private val takePictureLauncher = registerForActivityResult(ActivityResultContracts.TakePicturePreview()) { bitmap: Bitmap? ->
if (bitmap != null) {
val imageUri = bitmapToFile(bitmap, this)
Log.d("SearchFragment", "takePictureLauncher: $imageUri")
checkImageDialog(imageUri)
} else {
Log.d("SearchFragment", "takePictureLauncher: Bitmap is null")
}
}
private val selectImageFromGalleryLauncher = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->
uri?.let {
Log.d("SearchFragment", "selectImageFromGalleryLauncher: $uri")
checkImageDialog(uri)
}
}
- 사진을 찍고 갤러리에서 이미지를 선택하기 위한 activityResult를 등록합니다.
private fun bitmapToFile(bitmap: Bitmap, context: Context): Uri {
val fileName = "tempImage-${System.currentTimeMillis()}.jpg"
val directory = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
val imageFile = File(directory, fileName)
FileOutputStream(imageFile).use { outputStream ->
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, outputStream)
}
return Uri.fromFile(imageFile)
}
- 비트맵 이미지를 파일로 저장하고 서버로 전송하기 위해 URI로 반환합니다.