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

AndroidでDrawableをBitmapに変換する方法を徹底解説!サンプルコード付き

この記事では、Androidアプリ開発においてDrawableをBitmap(ビットマップ)に変換する方法を、実際に動作するサンプルコードとともに解説します。画像の加工・保存・送信などを行いたい場合、Bitmap形式への変換は頻繁に使われるテクニックなので、ぜひマスターしておきましょう。

手順1:Android Studioで新規プロジェクトを作成する

Android Studioを起動し、「File」⇒「New Project」を選択して新しいプロジェクトを作成します。プロジェクト名やパッケージ名など、必要な項目をすべて入力してください。テンプレートは「Empty Activity」で問題ありません。

手順2:レイアウトファイル(activity_main.xml)を編集する

res/layout/activity_main.xml に以下のコードを追加します。ImageViewと、変換を実行するためのButtonを配置した、シンプルな縦方向のLinearLayoutです。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    android:padding="4dp"
    android:gravity="center"
    tools:context=".MainActivity">
    <ImageView
    android:id="@+id/imageView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
    <Button
    android:id="@+id/btnConvert"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Convert Drawable to Bitmap"/>
</LinearLayout>

手順3:MainActivity.java を編集する

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

import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
    ImageView imageView;
    Button btnConvert;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = findViewById(R.id.imageView);
        btnConvert = findViewById(R.id.btnConvert);
        btnConvert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image);
                imageView.setImageBitmap(bitmap);
                Toast.makeText(getApplicationContext(), "Image converted to Bitmap",
                Toast.LENGTH_SHORT).show();
            }
        });
    }
}

変換の核心となるのは、次の一行です。

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image);

BitmapFactory.decodeResource() メソッドは、指定したリソースID(ここでは R.drawable.image)のDrawableをデコードし、Bitmapオブジェクトとして生成します。なお、あらかじめ res/drawable フォルダに「image」という名前の画像ファイルを配置しておく必要があります。生成されたBitmapは setImageBitmap() によってImageViewに表示され、Toastで変換完了が通知されます。

手順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" android:windowSoftInputMode="adjustPan">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

アプリを実行してみよう

それでは、アプリを実行してみましょう。実機のAndroidスマートフォンをPCに接続していることを前提とします。Android Studioでプロジェクト内のアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックします。接続したモバイルデバイスを選択すると、端末にアプリの初期画面が表示されます。

AndroidでDrawableをBitmapに変換する方法を徹底解説!サンプルコード付き

ボタンをタップすると、DrawableリソースがBitmapに変換されて画面に表示され、同時に「Image converted to Bitmap」というトーストメッセージが表示されます。

補足:任意のDrawableオブジェクトを汎用的にBitmapへ変換する方法

リソースIDからではなく、すでに取得済みのDrawableオブジェクトをBitmapに変換したい場合は、Canvasを利用した次のようなユーティリティメソッドが便利です。

public static Bitmap drawableToBitmap(Drawable drawable) {
    if (drawable instanceof BitmapDrawable) {
        return ((BitmapDrawable) drawable).getBitmap();
    }
    int width = Math.max(drawable.getIntrinsicWidth(), 1);
    int height = Math.max(drawable.getIntrinsicHeight(), 1);
    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);
    return bitmap;
}

このメソッドは、元がBitmapDrawableであればそのまま内部のBitmapを返し、それ以外の場合は新しいBitmapを作成してCanvas経由で描画します。ベクターdrawableやカスタムdrawableなど、さまざまな種類のDrawableに対応できる汎用的な実装です。

  1. Androidで画像をBase64文字列に変換する方法をステップごとに解説

    はじめに この記事では、Androidアプリで画像をBase64文字列に変換する方法を、実際のサンプルコードとともにステップ形式で解説します。 Base64とは、バイナリデータ(画像など)をテキスト形式の文字列として扱えるようにするエンコード方式です。画像データをWeb API経由で送受信したり、JSONに含めて保存したりする際によく利用されます。 実装手順 ステップ1:新規プロジェクトを作成する Android Studioを起動し、「File」→「New Project」を選択して新しいプロジェクトを作成します。必要な項目をすべて入力してプロジェクトをセットアップしましょう。 ステップ2:

  2. 【Android開発】Bitmap(ビットマップ)をDrawableに変換する方法をサンプルコード付きで解説

    この記事では、Androidアプリ開発においてBitmap(ビットマップ)をDrawableに変換する方法を、実際のサンプルコードとともにステップ形式で解説します。画像の描画やカスタムビューの実装などで頻繁に必要となる処理なので、ぜひ参考にしてください。 全体の流れ 本チュートリアルでは、ボタンをタップするとリソースから取得したDrawableをBitmapに変換し、さらにそのBitmapを新しいDrawableとしてImageViewに表示するというシンプルなアプリを作成します。 ステップ1:新規プロジェクトの作成 まず、Android Studioで新しいプロジェクトを作成します。メニュー