Monday, September 28, 2015

android - How to convert a bitmap to a byte array

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    tools:context=".MainActivity"
    android:background="#c9cdaf"
    >
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Convert Bitmap To Byte Array"
        />
    <ImageView
        android:id="@+id/iv_source"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/btn"
        />
    <ImageView
        android:id="@+id/iv_compressed"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/btn"
        android:layout_toRightOf="@id/iv_source"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.app.ActionBar;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;


public class MainActivity extends Activity {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the widgets reference from XML layout
        final RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
        final Button btn = (Button) findViewById(R.id.btn);
        final ImageView iv_source = (ImageView) findViewById(R.id.iv_source);
        final ImageView iv_compressed = (ImageView) findViewById(R.id.iv_compressed);

        final ActionBar ab = getActionBar();
        ab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FF94CDA5")));

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try{
                    // Create a bitmap from an asset image
                    InputStream is = getAssets().open("animals.png");
                    Bitmap bitmap = BitmapFactory.decodeStream(is);

                    iv_source.setImageBitmap(bitmap);

                    /*
                        ByteArrayOutputStream
                            A specialized OutputStream for class for writing content to an
                            (internal) byte array. As bytes are written to this stream, the byte
                            array may be expanded to hold more bytes. When the writing is
                            considered to be finished, a copy of the byte array can be
                            requested from the class.
                    */

                    /*
                        public synchronized byte[] toByteArray ()
                            Returns the contents of this ByteArrayOutputStream as a byte array.
                            Any changes made to the receiver after returning will not be
                            reflected in the byte array returned to the caller.

                            Returns
                            this stream's current contents as a byte array.
                    */

                    // Initializing a new ByteArrayOutputStream
                    ByteArrayOutputStream stream = new ByteArrayOutputStream();

                    /*
                        public boolean compress (Bitmap.CompressFormat format, int quality, OutputStream stream)
                            Write a compressed version of the bitmap to the specified outputstream.
                            If this returns true, the bitmap can be reconstructed by passing a
                            corresponding inputstream to BitmapFactory.decodeStream().

                            Note: not all Formats support all bitmap configs directly, so it is
                            possible that the returned bitmap from BitmapFactory could be in
                            a different bitdepth, and/or may have lost per-pixel alpha
                            (e.g. JPEG only supports opaque pixels).

                            Parameters
                            format : The format of the compressed image
                            quality : Hint to the compressor, 0-100. 0 meaning compress for small
                                size, 100 meaning compress for max quality. Some formats,
                                like PNG which is lossless, will ignore the quality setting
                            stream : The outputstream to write the compressed data.

                            Returns
                                true if successfully compressed to the specified stream.
                    */

                    // Compress the bitmap to jpeg format and 50% image quality
                    bitmap.compress(Bitmap.CompressFormat.JPEG,50,stream);

                    // Create a byte array from ByteArrayOutputStream
                    byte[] byteArray = stream.toByteArray();

                    /*
                        public static Bitmap decodeByteArray (byte[] data, int offset, int length)
                            Decode an immutable bitmap from the specified byte array.

                            Parameters
                            data : byte array of compressed image data
                            offset : offset into imageData for where the decoder should begin parsing.
                            length : the number of bytes, beginning at offset, to parse

                            Returns
                                The decoded bitmap, or null if the image could not be decoded.
                    */

                    // Create a bitmap from the byte array
                    Bitmap compressedBitmap = BitmapFactory.decodeByteArray(byteArray,0,byteArray.length);

                    // Set the compressed bitmap to second ImageView
                    iv_compressed.setImageBitmap(compressedBitmap);

                    // Notify the user that byte array generated from bitmap
                    Toast.makeText(getApplicationContext(),
                            "ByteArray created.",Toast.LENGTH_SHORT).show();
                }catch (IOException e) // Catch the exception
                {
                    e.printStackTrace();
                }
            }
        });
    }
}

More android examples