이 글에서는 Kotlin을 사용하여 안드로이드에서 이미지를 Base64 문자열로 변환하는 방법을 단계별로 알아봅니다. 이미지를 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" 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:textColor="@android:color/background_dark" android:textStyle="bold" /> </RelativeLayout>
3단계 — MainActivity.kt 코드 작성
src/MainActivity.kt 파일에 아래 코드를 추가합니다. 핵심 로직은 다음과 같습니다.
- BitmapFactory.decodeResource(): 리소스 폴더의 이미지를 Bitmap 객체로 디코딩합니다.
- bitmap.compress(): Bitmap을 JPEG 형식으로 압축하여 ByteArrayOutputStream에 저장합니다.
- Base64.encodeToString(): 바이트 배열을 Base64 인코딩된 문자열로 변환합니다.
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.util.Base64
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import java.io.ByteArrayOutputStream
class MainActivity : AppCompatActivity() {
lateinit var textView: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
textView = findViewById(R.id.textView)
val byteArrayOutputStream = ByteArrayOutputStream()
val bitmap = BitmapFactory.decodeResource(resources, R.drawable.image)
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream)
val imageBytes: ByteArray = byteArrayOutputStream.toByteArray()
val imageString: String = Base64.encodeToString(imageBytes, Base64.DEFAULT)
textView.text = imageString
}
}위 코드에서 압축 품질 값(100)은 원본 품질을 그대로 유지하는 설정입니다. 변환된 문자열 크기를 줄이고 싶다면 이 값을 50~80 사이로 낮추는 것도 좋은 방법입니다.
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.q11"> <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 문자열로 변환된 결과가 표시되는 것을 확인할 수 있습니다.
