【初心者でも安心】Androidアプリ開発で役立つDrawableからByte配列への変換ガイド

2024-07-27

AndroidでDrawableをByte配列に変換する方法

必要なもの

  • サンプル画像
  • Android Studio

手順

  1. DrawableをBitmapに変換する

    DrawableをByte配列に変換するには、まずBitmapに変換する必要があります。以下のコード例のように、drawableToBitmap() 関数を使用して変換できます。

    public static Bitmap drawableToBitmap(Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        }
    
        Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        drawable.draw(canvas);
        return bitmap;
    }
    
  2. BitmapをByte配列に変換する

    BitmapをByte配列に変換するには、ByteArrayOutputStreamcompress() メソッドを使用します。以下のコード例のように記述します。

    public static byte[] bitmapToByteArray(Bitmap bitmap) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); // PNG形式に圧縮
        return stream.toByteArray();
    }
    
  3. 上記1、2の手順を組み合わせることで、DrawableをByte配列に変換できます。

    public static byte[] drawableToByteArray(Drawable drawable) {
        Bitmap bitmap = drawableToBitmap(drawable);
        return bitmapToByteArray(bitmap);
    }
    
ImageView imageView = findViewById(R.id.imageView);
Drawable drawable = imageView.getDrawable();
byte[] byteArray = drawableToByteArray(drawable);
Log.d("TAG", "Byte array: " + Arrays.toString(byteArray));

注意点

  • 大容量の画像を扱う場合は、メモリ使用量に注意する必要があります。
  • 上記のコードはあくまで一例であり、状況に応じて圧縮形式や画質などを調整する必要があります。



import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.util.Base64;

import java.io.ByteArrayOutputStream;

public class DrawableToByteArray {

    public static byte[] drawableToByteArray(Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
            return bitmapToByteArray(bitmap);
        }

        Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        drawable.draw(canvas);
        return bitmapToByteArray(bitmap);
    }

    public static byte[] bitmapToByteArray(Bitmap bitmap) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        byte[] byteArray = stream.toByteArray();
        return byteArray;
    }

    public static String drawableToBase64String(Drawable drawable) {
        byte[] byteArray = drawableToByteArray(drawable);
        return Base64.encodeToString(byteArray, Base64.DEFAULT);
    }

    public static Bitmap base64StringToBitmap(String base64String) {
        byte[] byteArray = Base64.decode(base64String, Base64.DEFAULT);
        return BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
    }
}

To use this code, you can first get a reference to the Drawable you want to convert. For example, if you have an ImageView with an image in it, you can get the Drawable like this:

ImageView imageView = findViewById(R.id.imageView);
Drawable drawable = imageView.getDrawable();

Once you have the Drawable, you can call the drawableToByteArray() method to convert it to a byte array. For example:

byte[] byteArray = DrawableToByteArray.drawableToByteArray(drawable);

You can also convert the Drawable to a Base64 string using the drawableToBase64String() method:

String base64String = DrawableToByteArray.drawableToBase64String(drawable);

To convert a Base64 string back to a Bitmap, you can use the base64StringToBitmap() method:

Bitmap bitmap = DrawableToByteArray.base64StringToBitmap(base64String);



The getPixelArray() method can be used to get the pixel data of a Drawable as an array of integers. This data can then be converted to a byte array using the Arrays.toString() method.

public static byte[] drawableToByteArrayUsingPixelArray(Drawable drawable) {
    int width = drawable.getIntrinsicWidth();
    int height = drawable.getIntrinsicHeight();
    int[] pixels = new int[width * height];
    drawable.getPixelArray(pixels, 0, width);
    String pixelString = Arrays.toString(pixels);
    return pixelString.getBytes();
}

Using the NinePatchChunk class

The NinePatchChunk class can be used to decode a Nine-Patch image from a Drawable. The NinePatchChunk class has a getBitmap() method that can be used to get the Bitmap representation of the Nine-Patch image. This Bitmap can then be converted to a byte array using the bitmapToByteArray() method described above.

public static byte[] drawableToByteArrayUsingNinePatchChunk(Drawable drawable) {
    if (!(drawable instanceof NinePatchDrawable)) {
        return null;
    }

    NinePatchDrawable ninePatchDrawable = (NinePatchDrawable) drawable;
    NinePatchChunk ninePatchChunk = ninePatchDrawable.getNinePatchChunk();
    Bitmap bitmap = ninePatchChunk.getBitmap();
    return bitmapToByteArray(bitmap);
}

Using a third-party library

There are a number of third-party libraries available that can be used to convert Drawables to byte arrays. One popular library is Glide. Glide has a toBytes() method that can be used to convert a Drawable to a byte array.

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;

public static byte[] drawableToByteArrayUsingGlide(Drawable drawable) {
    try {
        return Glide.with(context)
                .load(drawable)
                .asBitmap()
                .into(new Target<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Target<Bitmap> glideTarget) {
                        ByteArrayOutputStream stream = new ByteArrayOutputStream();
                        resource.compress(Bitmap.CompressFormat.PNG, 100, stream);
                        byte[] byteArray = stream.toByteArray();
                    }

                    @Override
                    public void onLoadFailed(@Nullable Drawable errorDrawable) {
                        // Handle error
                    }

                    @Override
                    public void onCleared() {
                        // Cleanup
                    }
                })
                .get();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

android database drawable



.NET Framework と SQLite を使用して XSD データセットに基づいて SQLite データベースを作成する方法

このチュートリアルを完了するには、次のものが必要です。SQLite ADO. NET プロバイダ.NET Framework 4.7 以降Visual Studio 2019 以降Visual Studio で新しい C# コンソール アプリケーション プロジェクトを作成します。...


Subversion を使用したデータベース構造変更のバージョン管理

データベース構造変更をバージョン管理システムで管理することは、データベースの開発と運用において非常に重要です。バージョン管理システムを使用することで、以下のメリットを得ることができます。コラボレーション: 複数の開発者がデータベース構造変更を同時に作業し、変更内容を統合することができます。...


ALTER TABLE文でユニークインデックス列の値を入れ替える

方法1:UPDATE文を使用する最も簡単な方法は、UPDATE文を使用して、直接値を入れ替えることです。例:この方法では、WHERE条件で特定のレコードのみを対象に値を入れ替えることができます。方法2:CASE式を使用するCASE式を使用して、値を入れ替える条件を指定することもできます。...


DB2 PHPドライバーを使ってIBM i(AS/400)データベースに接続する

必要なものIBM i(AS/400)データベースへの接続情報ODBCドライバーPHP手順ODBCドライバーのインストール IBM i(AS/400)に接続するには、IBMから提供されているODBCドライバーをインストールする必要があります。 Windowsの場合 IBM i Access Client Solutions for Windowsをダウンロードします。 ダウンロードしたファイルをインストールします。 インストール時に「ODBC Driver for iSeries」を選択肢ます。 Linuxの場合...


SQLite、RavenDB、Firebird:.NET開発者のための最適な埋め込みデータベースの選択

代表的な埋め込みデータベースネットワーク上で動作する埋め込みデータベースの選択ネットワーク上で動作する埋め込みデータベースを選択する際には、以下の要素を考慮する必要があります。ライセンス: データベースのライセンスはどのようになっていますか?オープンソースのデータベースは無料で使用できますが、商用データベースにはライセンス費用がかかります。...



SQL SQL SQL SQL Amazon で見る



ストアドプロシージャ、ライブラリ、フレームワーク...MySQLでバイナリデータを扱うためのツール

TEXT:可変長の文字列型。最大65, 535バイトから4GBまで保存できます。バイナリデータだけでなく、文字列も保存できます。BLOB:可変長のバイナリデータ型。最大65, 535バイトから4GBまで保存できます。VARBINARY:可変長のバイナリデータ型。最大65


アプリケーションロジックでテーブル更新を制御する方法

MySQLトリガーは、特定のデータベース操作に対して自動的に実行されるコードです。トリガーを使用して、テーブル更新を防止するエラーをスローすることができます。例:以下の例は、usersテーブルのage列が18歳未満の場合に更新を防止するトリガーです。


初心者でも安心!PHPでフラットファイルデータベースを始めるためのガイド

PHPは、Web開発に広く使用されているプログラミング言語です。SQLは、データベースとのやり取りに使用される構造化照会言語です。フラットファイルデータベースは、PHPとSQLを使用して読み書きできます。費用を抑えられるサーバーの負荷が少ない


データベースアプリケーションにおける XSD データセットと外部キーの重要性

XSD データセットは、XML スキーマ定義 (XSD) を使用して定義されたデータの集合です。.NET では、DataSet クラスを使用して XSD データセットを表します。外部キーは、データベースの 2 つのテーブル間の関連を表す制約です。XSD データセットでは、ForeignKeyConstraint クラスを使用して外部キーを表します。


SQL Serverデータベースのバージョン管理:Subversionとの連携方法

この解説では、Subversion(SVN)と呼ばれるバージョン管理システムを用いて、SQL Serverデータベースのバージョン管理を行う方法について説明します。SVNは、ファイルやディレクトリのバージョン管理に広く用いられるオープンソースツールであり、データベースのバージョン管理にも活用できます。