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

안드로이드 앱에서 카메라 사용하는 방법 – 단계별 구현 가이드

이 튜토리얼에서는 안드로이드 앱에서 카메라 기능을 구현하는 방법을 단계별로 살펴봅니다. 카메라 인텐트(MediaStore.ACTION_IMAGE_CAPTURE)를 활용하면 복잡한 카메라 API를 직접 제어하지 않고도 기기의 기본 카메라 앱을 호출해 사진을 촬영하고, 그 결과를 앱 화면에 바로 표시할 수 있습니다.

1단계: 새 프로젝트 생성

Android Studio를 실행한 뒤 File → New Project 메뉴로 이동하고, 필요한 항목을 모두 입력하여 새 프로젝트를 생성합니다.

2단계: 레이아웃 XML 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 화면 하단에는 '사진 촬영' 버튼을 배치하고, 그 위 영역에는 촬영된 사진을 보여줄 ImageView를 배치한 구성입니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="사진 촬영" />
    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/button1"
        android:layout_alignParentTop="true" />
</RelativeLayout>

3단계: MainActivity 코드 작성

src/MainActivity.java 파일에 다음 코드를 추가합니다. 버튼을 클릭하면 카메라 인텐트가 실행되고, 촬영 결과는 onActivityResult() 콜백에서 Bitmap으로 받아 ImageView에 표시됩니다.

package com.example.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {
    private static final int CAMERA_REQUEST = 1888;
    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = (ImageView) this.findViewById(R.id.imageView1);
        Button photoButton = (Button) this.findViewById(R.id.button1);
        photoButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(cameraIntent, CAMERA_REQUEST);
            }
        });
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CAMERA_REQUEST) {
            Bitmap photo = (Bitmap) data.getExtras().get("data");
            imageView.setImageBitmap(photo);
        }
    }
}

4단계: 매니페스트 설정

Manifests/AndroidManifest.xml 파일이 아래 코드와 같이 구성되어 있는지 확인하고, 누락된 부분이 있다면 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.example.myapplication">
    <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 아이콘을 클릭하세요. 기기 선택 목록에서 자신의 모바일 기기를 고르면, 해당 기기에 아래와 같은 기본 화면이 나타납니다.

안드로이드 앱에서 카메라 사용하는 방법 – 단계별 구현 가이드

안드로이드 앱에서 카메라 사용하는 방법 – 단계별 구현 가이드

참고: 최신 Android 개발 환경이라면

위 예제에서 사용한 startActivityForResult()onActivityResult()는 현재 공식적으로 지원이 중단(deprecated)된 방식입니다. AndroidX 기반의 최신 프로젝트에서는 Activity Result API의 ActivityResultContracts.TakePicturePreview()를 사용하는 것이 권장되며, 카메라를 호출하고 결과를 처리한다는 전체적인 흐름은 본 예제와 동일합니다.