안드로이드 앱에서 Base64 문자열을 비트맵(Bitmap) 이미지로 변환하는 방법
이 예제는 안드로이드에서 Base64로 인코딩된 문자열을 비트맵 이미지로 변환하는 방법을 단계별로 보여줍니다. 서버와 통신하거나 데이터베이스에 이미지를 저장할 때 이미지를 Base64 문자열 형태로 주고받는 경우가 많은데, 이를 다시 화면에 표시할 수 있는 비트맵으로 디코딩하는 과정을 함께 살펴보겠습니다.
1단계 — 새 프로젝트 생성
Android Studio에서 File → New Project로 이동한 뒤, 프로젝트 생성에 필요한 모든 정보를 입력하여 새 프로젝트를 만듭니다.
2단계 — 레이아웃 XML 작성
res/layout/activity_main.xml 파일에 아래 코드를 추가합니다.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_horizontal" android:orientation="vertical" android:padding="16dp"> <ImageView android:id="@+id/imageView" android:layout_width="match_parent" android:layout_height="match_parent" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Base64 string into a BitMap image in Android App" android:textSize="16sp" android:textStyle="bold|italic" /> </LinearLayout>
3단계 — MainActivity 자바 코드 작성
src/MainActivity.java 파일에 아래 코드를 추가합니다.
이 코드의 핵심 흐름은 다음과 같습니다.
- 프로젝트 리소스의 이미지를 비트맵으로 불러온 뒤 PNG 형식(품질 100)으로 압축하여 바이트 배열로 변환합니다.
- 바이트 배열을
Base64.encodeToString()으로 인코딩해 문자열을 생성합니다. - 해당 문자열을 다시
Base64.decode()로 디코딩한 후,BitmapFactory.decodeByteArray()로 비트맵을 복원하여 ImageView에 표시합니다.
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Base64;
import android.widget.ImageView;
import java.io.ByteArrayOutputStream;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
ImageView imageView;
@SuppressLint("WrongThread")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] imageBytes = byteArrayOutputStream.toByteArray();
String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);
imageBytes = Base64.decode(imageString, Base64.DEFAULT);
Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
imageView.setImageBitmap(decodedImage);
}
}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
아이콘을 클릭하세요. 목록에서 사용 중인 모바일 기기를 선택하면, 기기 화면에 변환된 이미지가 아래와 같이 표시됩니다.
