개요
이 글에서는 안드로이드 앱에서 이미지를 Base64 문자열로 변환하는 방법을 단계별 예제와 함께 살펴봅니다. Base64 인코딩은 이미지 데이터를 텍스트 형태로 변환하여 서버 전송, 데이터베이스 저장, JSON 응답 처리 등에 활용할 수 있는 유용한 기술입니다.
Base64란 무엇인가?
Base64는 바이너리 데이터를 64개의 ASCII 문자 조합으로 표현하는 인코딩 방식입니다. 이미지 파일을 텍스트 기반 포맷에 담아 주고받아야 할 때 널리 사용되며, 안드로이드에서는 android.util.Base64 클래스를 통해 손쉽게 사용할 수 있습니다.
구현 단계
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" tools:context=".MainActivity"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/textView" android:padding="4dp"/> </RelativeLayout>
레이아웃에는 변환 결과를 표시할 TextView 하나만 배치했습니다.
3단계: 이미지 준비
변환할 이미지를 res/drawable 폴더에 복사하여 붙여넣습니다. 예를 들어 res/drawable/logo.png처럼 저장합니다.
4단계: MainActivity 코드 작성
src/MainActivity.java 파일에 아래 코드를 추가합니다.
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.widget.TextView;
import java.io.ByteArrayOutputStream;
public class MainActivity extends AppCompatActivity {
TextView textView;
String string;
Bitmap bitmap;
@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 = BitmapFactory.decodeResource(getResources(),R.drawable.logo);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byte[] bytes = byteArrayOutputStream.toByteArray();
string = Base64.encodeToString(bytes, Base64.DEFAULT);
textView.setText(string);
}
}핵심 코드 흐름
- BitmapFactory.decodeResource() – drawable 리소스의 이미지를 Bitmap 객체로 디코딩합니다.
- bitmap.compress() – Bitmap을 JPEG 형식(품질 100)으로 ByteArrayOutputStream에 압축하여 바이트 배열로 변환합니다.
- Base64.encodeToString() – 바이트 배열을 Base64 문자열로 인코딩합니다.
- 마지막으로 TextView에 변환된 문자열을 출력합니다.
참고로 최신 Android Studio 프로젝트에서는 지원 중단된 android.support.v7.app.AppCompatActivity 대신 androidx.appcompat.app.AppCompatActivity를 사용하는 것이 좋습니다.
5단계: 매니페스트 설정
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로 변환된 긴 문자열이 표시되는 것을 확인할 수 있습니다.

마무리 및 참고 사항
이렇게 안드로이드에서 이미지를 Base64 문자열로 변환하는 과정을 알아보았습니다. 이 방법은 이미지 업로드 API 구현, 채팅 앱의 이미지 전송 등 다양한 상황에서 활용할 수 있습니다. 다만 Base64로 인코딩된 데이터는 원본 대비 약 33% 크기가 커지므로, 고해상도 이미지를 다룰 때는 메모리 사용량과 성능을 함께 고려하는 것이 좋습니다. 또한 UI 스레드에서 무거운 이미지 변환 작업을 수행하면 ANR(응답 없음) 오류가 발생할 수 있으므로, 실제 프로덕션 환경에서는 백그라운드 스레드나 코루틴을 활용하는 것을 권장합니다.