How to convert drawable to Byte Array in Android

In this android programming code example, we are going show you how to convert drawable to byte array in android.

If you have a drawable in your project that you will like to convert to a byte array for post processing or storage, you can follow the steps below.

STEPS

  1. Get the instance of the ImageView in your Activity class.
  2. Call ImageView getDrawable() method to get a drawable object.
  3. Get a Bitmap object from the drawable object using the getBitmap() method.
  4. Create an instance of ByteArrayOutputStream object.
  5. Add the bitmap object to the stream using compress() method
  6. Convert the stream to byteArray using toByteArray() method

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/camera"/>


</LinearLayout>

MainActivity.java

package com.inducesmile.buttonsnippets;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.ImageView;

import java.io.ByteArrayOutputStream;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();

    @SuppressLint("WrongThread")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ImageView imageView= findViewById(R.id.imageView2);

        Drawable d = imageView.getDrawable();
        Bitmap bitmap = ((BitmapDrawable)d).getBitmap();
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        byte[] bitmapdata = stream.toByteArray();
    }
}

If you have any questions or suggestions kindly use the comment box or you can contact us directly through our contact page below.

 

Add a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.