이 튜토리얼에서는 안드로이드에서 이미지를 Base64 문자열로 변환하는 방법을 단계별로 살펴봅니다. Base64 인코딩은 이미지 데이터를 텍스트 형태로 변환해 주기 때문에 서버 전송, 데이터베이스 저장, JSON 응답 처리 등 다양한 상황에서 유용하게 활용됩니다.
1단계 — 새 프로젝트 만들기
Android Studio에서 새 프로젝트를 생성합니다. 상단 메뉴에서 File → New Project를 선택한 뒤, 프로젝트 생성에 필요한 세부 정보를 모두 입력합니다.
2단계 — 레이아웃 파일 수정
res/layout/activity_main.xml 파일에 아래 코드를 추가합니다.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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:padding="8dp" tools:context=".MainActivity"> <TextView android:id="@+id/textView" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_centerInParent="true" android:textSize="12sp" android:textStyle="bold" /> </RelativeLayout>
레이아웃은 화면 전체를 채우는 하나의 TextView로 구성되어 있으며, 이 TextView에 변환된 Base64 문자열이 출력됩니다.
3단계 — MainActivity 코드 작성
src/MainActivity.java 파일에 아래 코드를 추가합니다.
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Base64;
import android.widget.TextView;
import java.io.ByteArrayOutputStream;
public class MainActivity extends AppCompatActivity {
TextView textView;
@SuppressLint("WrongThread")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.instaimage);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byte[] imageBytes = byteArrayOutputStream.toByteArray();
String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);
textView.setText(imageString);
}
}
핵심 코드 설명
- BitmapFactory.decodeResource(): drawable 폴더의 이미지(
R.drawable.instaimage)를 Bitmap 객체로 불러옵니다. 실제 프로젝트에 있는 이미지 리소스 이름으로 변경하세요. - bitmap.compress(): Bitmap을 JPEG 형식(품질 100)으로 압축하여 ByteArrayOutputStream에 기록합니다.
- toByteArray(): 스트림에 담긴 이미지 데이터를 byte 배열로 가져옵니다.
- Base64.encodeToString(): byte 배열을 Base64 문자열로 인코딩합니다.
이미지 변환 작업은 용량에 따라 시간이 걸릴 수 있으므로, 실제 앱에서는 백그라운드 스레드나 코루틴에서 처리하는 것이 좋습니다.
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"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
앱 실행 및 결과 확인
이제 애플리케이션을 실행해 결과를 확인해 보겠습니다. 실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run
아이콘을 클릭합니다. 기기 목록에서 본인의 모바일 기기를 선택하면, 앱이 실행되면서 화면에 이미지가 Base64 문자열로 변환된 결과가 표시되는 것을 확인할 수 있습니다.
