Android
 Computer >> コンピューター >  >> プログラミング >> Android

【Android開発】Base64文字列をBitmap画像に変換して表示する方法を徹底解説

はじめに

Androidアプリ開発では、サーバーとのAPI通信などで画像データをBase64形式の文字列として受け取り、それをBitmap画像に変換して画面に表示したいケースがよくあります。本記事では、その基本的な実装方法をサンプルコード付きでステップごとに解説します。

処理の流れ

今回のサンプルでは、リソース画像をBitmapとして読み込み、PNG形式で圧縮したうえでBase64文字列にエンコードします。その後、Base64文字列を再びバイト配列へデコードし、BitmapFactoryを使ってBitmap画像に復元してImageViewに表示するという、一連の流れを実装しています。

ステップ1:新規プロジェクトの作成

Android Studioを起動し、「File」→「New Project」を選択して新しいプロジェクトを作成します。必要な情報を入力してプロジェクトをセットアップしてください。

ステップ2:レイアウトファイル(activity_main.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.java の編集

src/MainActivity.java に以下のコードを追加します。

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);
    }
}

コードのポイント

  • BitmapFactory.decodeResource():drawableリソースからBitmap画像を読み込みます。
  • bitmap.compress():BitmapをPNG形式で圧縮し、ByteArrayOutputStreamへ書き出します。
  • Base64.encodeToString():バイト配列をBase64文字列にエンコードします。
  • Base64.decode():Base64文字列を元のバイト配列にデコードします。
  • BitmapFactory.decodeByteArray():バイト配列からBitmap画像を生成し、ImageViewにセットします。

ステップ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端末をパソコンに接続していることを前提とします。Android Studioからアプリを実行するには、プロジェクト内のいずれかのアクティビティファイルを開き、ツールバーの「Run」【Android開発】Base64文字列をBitmap画像に変換して表示する方法を徹底解説アイコンをクリックしてください。表示された候補から自分のモバイルデバイスを選択すると、端末上にBase64文字列から復元された画像が表示されます。

【Android開発】Base64文字列をBitmap画像に変換して表示する方法を徹底解説

  1. WordPressサイトをAndroidアプリに変換する方法【初心者向け完全ガイド】

    モバイルデバイスの普及により、小さな画面でインターネットを閲覧する人がますます増えています。WordPressでサイトを運営しているなら、すべての訪問者にとって見やすいサイトにする方法の一つが、レスポンシブ対応テーマの選択です。レスポンシブテーマは、ユーザーの画面サイズに応じて自動的にレイアウトを調整してくれます。また、モバイルデバイスはPCよりも通信速度が遅いネットワークで動作することも考慮が必要です。そのため、読み込みが速いウェブサイトであることが重要になります。サイト自体の軽量化に加えて、ホスティングプロバイダーがボトルネックになっていないかも確認しましょう。もしホスティング環境が速度を

  2. AndroidでOCRを使って画像をテキストに変換する方法【おすすめアプリ2選】

    OCR(光学文字認識)技術はここ数年で大きく進化し、画像からテキストをかなり高精度で読み取れるようになりました。スマートフォン1台で画像内の文字をそのままテキスト化できれば、わざわざパソコンに画像を転送してオンラインで変換する手間が省け、とても便利です。この記事では、Androidデバイスを使って画像をテキストに変換する方法をご紹介します。 Androidで画像をテキストに変換する方法 Google PlayストアにはOCR対応アプリが数多く公開されていますが、すべてが期待通りの精度を発揮するわけではありません。さまざまなアプリを実際に検証した結果、特に高い精度を実現していたのがMicros