Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

안드로이드에서 프로그래밍 방식으로 카메라 사진 촬영 구현하기 (Kotlin 예제)

이 튜토리얼에서는 안드로이드 앱에서 프로그래밍 방식으로 카메라를 호출해 사진을 촬영하고, 촬영한 이미지를 화면에 표시하는 방법을 단계별로 살펴봅니다. Kotlin을 기반으로 진행하며, 카메라 권한 요청, MediaStore를 활용한 이미지 저장, 촬영 결과 처리까지 전체 과정을 다룹니다.

구현 단계

1단계 — 새 프로젝트 생성

Android Studio에서 File → New Project를 선택한 후, 필요한 정보를 모두 입력하여 새 프로젝트를 생성합니다. 이때 언어는 Kotlin으로 선택합니다.

2단계 — 레이아웃 작성 (activity_main.xml)

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 화면 상단에는 안내 문구가, 중앙에는 촬영된 이미지를 보여줄 ImageView가, 하단에는 촬영 버튼이 배치됩니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="4dp">
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@id/imageView"
    android:layout_centerInParent="true"
    android:layout_marginBottom="10dp"
    android:text="아래 버튼을 누르면 카메라로 사진을 촬영합니다"
    android:textAlignment="center"
    android:textColor="@android:color/holo_purple"
    android:textSize="16sp"
    android:textStyle="bold" />
<ImageView
    android:id="@+id/imageView"
    android:layout_width="match_parent"
    android:layout_height="630dp"
    android:layout_above="@id/btnCaptureImage"
    android:layout_marginTop="16dp"
    android:scaleType="centerCrop"
    android:src="@drawable/ic_baseline_image_24" />
<Button
    android:id="@+id/btnCaptureImage"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:text="사진 촬영" />
</RelativeLayout>

3단계 — 메인 액티비티 작성 (MainActivity.kt)

src/MainActivity.kt 파일에 아래 코드를 추가합니다. 버튼을 누르면 먼저 카메라 권한 여부를 확인하고, 권한이 없으면 요청을 보낸 뒤 승인 결과에 따라 카메라를 실행합니다. 촬영이 완료되면 MediaStore에 저장된 이미지 URI를 통해 ImageView에 사진을 표시합니다.

import android.Manifest
import android.content.ContentValues
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.widget.Button
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat

class MainActivity : AppCompatActivity() {
    private lateinit var imageView: ImageView
    private lateinit var imageUri: Uri
    private val permissionCode = 1000
    private val imageCaptureCode = 1001

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"
        imageView = findViewById(R.id.imageView)
        val button = findViewById<Button>(R.id.btnCaptureImage)

        button.setOnClickListener {
            if (ContextCompat.checkSelfPermission(
                    this,
                    Manifest.permission.CAMERA
                ) == PackageManager.PERMISSION_GRANTED
            ) {
                openCamera()
            } else {
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(Manifest.permission.CAMERA),
                    permissionCode
                )
            }
        }
    }

    private fun openCamera() {
        val values = ContentValues().apply {
            put(MediaStore.Images.Media.TITLE, "New Picture")
            put(MediaStore.Images.Media.DESCRIPTION, "From the Camera")
        }
        imageUri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)!!
        val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
        startActivityForResult(cameraIntent, imageCaptureCode)
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == permissionCode) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openCamera()
            } else {
                Toast.makeText(this, "권한이 거부되었습니다.", Toast.LENGTH_SHORT).show()
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == imageCaptureCode && resultCode == RESULT_OK) {
            imageView.setImageURI(imageUri)
        }
    }
}

참고: 일부 자료에서는 권한 검사 조건이 반대로 작성되어 실제 기기에서 의도대로 동작하지 않는 경우가 있습니다. 위 코드는 권한이 이미 승인된 경우 즉시 카메라를 열고, 그렇지 않으면 권한을 요청하도록 올바르게 정리했습니다. 또한 startActivityForResult()는 최신 안드로이드 API에서 deprecated되었으므로, 새 프로젝트에서는 ActivityResultContracts.TakePicture()와 함께 Activity Result API를 사용하는 것이 좋습니다.

4단계 — 매니페스트 권한 설정 (AndroidManifest.xml)

AndroidManifest.xml 파일에 카메라 사용 권한과 외부 저장소 쓰기 권한을 선언합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.example.q11">
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

앱 실행 및 결과 확인

실제 안드로이드 기기를 컴퓨터에 연결한 상태에서 Android Studio 툴바의 Run(실행) 아이콘을 클릭합니다. 기기 목록에서 본인의 스마트폰을 선택하면 앱이 설치되고 기본 화면이 나타납니다.

팁: 카메라 기능은 에뮬레이터보다 실제 기기에서 테스트하는 것이 훨씬 정확하고 안정적입니다.

안드로이드에서 프로그래밍 방식으로 카메라 사진 촬영 구현하기 (Kotlin 예제)

안드로이드에서 프로그래밍 방식으로 카메라 사진 촬영 구현하기 (Kotlin 예제)

안드로이드에서 프로그래밍 방식으로 카메라 사진 촬영 구현하기 (Kotlin 예제)