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

안드로이드에서 Drawable을 Bitmap으로 변환하는 방법 (단계별 예제)

이 튜토리얼에서는 안드로이드 앱 개발 시 Drawable을 Bitmap으로 변환하는 방법을 단계별로 알아봅니다. 이미지 리소스를 픽셀 단위로 처리하거나 편집해야 할 때 자주 사용되는 기법이므로, 전체 예제 코드와 함께 자세히 살펴보겠습니다.

Drawable과 Bitmap의 차이점

안드로이드에서 Drawable은 화면에 그릴 수 있는 모든 그래픽 요소를 추상화한 개념입니다. 반면 Bitmap은 실제 픽셀 데이터로 구성된 이미지 객체로, 픽셀 조작, 파일 저장, 캔버스에 직접 그리기 등의 작업에 적합합니다. 따라서 이미지 편집 기능이나 고급 그래픽 처리가 필요할 때는 Drawable을 Bitmap으로 변환하는 과정이 필수적입니다.

1단계: 새 프로젝트 생성

Android Studio를 실행한 후 File ⇒ New Project 메뉴로 이동하여, 새 프로젝트 생성에 필요한 모든 정보를 입력하고 프로젝트를 만듭니다.

2단계: 레이아웃 XML 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. ImageView와 변환 버튼 하나로 구성된 간단한 레이아웃입니다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="4dp"
    android:gravity="center"
    tools:context=".MainActivity">
    <ImageView
    android:id="@+id/imageView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
    <Button
    android:id="@+id/btnConvert"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Convert Drawable to Bitmap"/>
</LinearLayout>

3단계: MainActivity.java 작성

src/MainActivity.java 파일에 아래 코드를 추가합니다.

import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
    ImageView imageView;
    Button btnConvert;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = findViewById(R.id.imageView);
        btnConvert = findViewById(R.id.btnConvert);
        btnConvert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image);
                imageView.setImageBitmap(bitmap);
                Toast.makeText(getApplicationContext(), "Image converted to Bitmap",
                Toast.LENGTH_SHORT).show();
            }
        });
    }
}

코드 핵심 로직: 버튼을 클릭하면 BitmapFactory.decodeResource() 메서드가 drawable 폴더의 이미지 리소스를 읽어 Bitmap 객체로 디코딩합니다. 이후 변환된 Bitmap을 setImageBitmap()으로 ImageView에 표시하고, Toast 메시지를 통해 변환이 성공했음을 사용자에게 알려줍니다.

4단계: AndroidManifest.xml 설정

androidManifest.xml 파일에 아래 코드를 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.com.sample">
    <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" android:windowSoftInputMode="adjustPan">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기를 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바에서 Run(실행) 아이콘을 클릭하세요. 목록에서 본인의 모바일 기기를 선택하면, 기기 화면에 앱이 실행되는 것을 확인할 수 있습니다.

안드로이드에서 Drawable을 Bitmap으로 변환하는 방법 (단계별 예제)

마무리

이처럼 BitmapFactory.decodeResource()를 활용하면 drawable 리소스를 손쉽게 Bitmap으로 변환할 수 있습니다. 참고로 VectorDrawable과 같은 벡터 형식의 리소스를 변환할 때는 이 방식 대신 Bitmap.createBitmap()과 Canvas를 조합하는 방법을 사용해야 한다는 점도 함께 기억해 두시면 좋습니다.