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

AndroidでJavaのBitmapをバイト配列(byte[])に変換する方法【サンプルコード付き】

このチュートリアルでは、Androidアプリ開発において、JavaのBitmap(ビットマップ)画像をバイト配列(byte[])へ変換する方法を、ステップごとに詳しく解説します。画像の圧縮・保存やネットワーク送信など、さまざまな場面で役立つ基本テクニックです。

ステップ1:新規プロジェクトを作成する

まずはAndroid Studioを起動し、メニューから「File」→「New Project」を選択しましょう。必要な項目をすべて入力して、新しいプロジェクトを作成します。

ステップ2:レイアウトファイル(activity_main.xml)を編集する

res/layout/activity_main.xml に以下のコードを追加します。このレイアウトには、変換を実行するためのButtonが1つと、元画像と圧縮後の画像を並べて表示するためのImageViewが2つ配置されています。

<RelativeLayout
   xmlns:android="https://schemas.android.com/apk/res/android"
   xmlns:tools="https://schemas.android.com/tools"
   android:id="@+id/rl"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:padding="10dp"
   tools:context=".MainActivity">
   <Button
      android:id="@+id/button"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="25sp"
      android:text="Convert Bitmap To Byte Array" />
   <ImageView
      android:id="@+id/ivSource"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_below="@id/button" />
   <ImageView
      android:id="@+id/ivCompressed"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_below="@id/button"
      android:layout_toRightOf="@id/ivSource" />
</RelativeLayout>

ステップ3:MainActivity.java を編集する

次に、src/MainActivity.java に以下のコードを記述します。ポイントとなるのは、ByteArrayOutputStreambitmap.compress()メソッドの組み合わせです。assetsフォルダから読み込んだ「image.png」をBitmapとして取得し、JPEG形式・品質80で圧縮しながらバイト配列へ変換しています。さらに、変換後のバイト配列から BitmapFactory.decodeByteArray() を使ってBitmapを復元し、画面に表示して結果を確認できるようにしています。

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
   Button button;
   ImageView ivSource, ivCompressed;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      button = findViewById(R.id.button);
      ivCompressed = findViewById(R.id.ivCompressed);
      ivSource = findViewById(R.id.ivSource);
      button.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            try {
               InputStream inputStream = getAssets().open("image.png");
               Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
               ivSource.setImageBitmap(bitmap);
               ByteArrayOutputStream stream = new ByteArrayOutputStream();
               bitmap.compress(Bitmap.CompressFormat.JPEG,80,stream);
               byte[] byteArray = stream.toByteArray();
               Bitmap compressedBitmap = BitmapFactory.decodeByteArray(byteArray,0,byteArray.length);
               ivCompressed.setImageBitmap(compressedBitmap);
               Toast.makeText(getApplicationContext(),
               "ByteArray created..",
               Toast.LENGTH_SHORT).show();
            } catch (IOException e) {
               e.printStackTrace();
            }
         }
      });
   }
}

ステップ4:AndroidManifest.xml を編集する

続いて、androidManifest.xml に以下のコードを追加します。外部ストレージへ書き込む可能性を考慮し、WRITE_EXTERNAL_STORAGE パーミッションを宣言しておきましょう。

<?xml version="1.0" encoding="utf-8"?>
<manifest
   xmlns:android="https://schemas.android.com/apk/res/android"
   package="app.com.sample">
   <uses-permission
      android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
   <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でJavaのBitmapをバイト配列(byte[])に変換する方法【サンプルコード付き】

AndroidでJavaのBitmapをバイト配列(byte[])に変換する方法【サンプルコード付き】

まとめ

ByteArrayOutputStream と bitmap.compress() を組み合わせることで、Bitmapを簡単にバイト配列へ変換できます。また、逆方向の変換には BitmapFactory.decodeByteArray() を使えばOKです。この手法は、画像データのデータベース保存、SharedPreferencesへの格納、サーバーへのアップロードなど、多くのシーンで応用できるので、ぜひマスターしておきましょう。

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

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

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

    この記事では、Androidアプリ開発においてDrawableをBitmap(ビットマップ)に変換する方法を、実際に動作するサンプルコードとともに解説します。画像の加工・保存・送信などを行いたい場合、Bitmap形式への変換は頻繁に使われるテクニックなので、ぜひマスターしておきましょう。 手順1:Android Studioで新規プロジェクトを作成する Android Studioを起動し、「File」⇒「New Project」を選択して新しいプロジェクトを作成します。プロジェクト名やパッケージ名など、必要な項目をすべて入力してください。テンプレートは「Empty Activity」で問題あ