Monday, September 28, 2015

android - How to convert drawable to 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="#f5f1ef"
    >
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Convert Drawable To Byte Array"
        />
    <ImageView
        android:id="@+id/iv_source"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/btn"
        android:padding="10dp"
        />
    <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"
        android:padding="10dp"
        />
</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.graphics.Bitmap;
import android.graphics.BitmapFactory;
import java.io.ByteArrayOutputStream;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.BitmapDrawable;


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("#FF6BB3F5")));

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /*
                    Drawable
                        A Drawable is a general abstraction for "something that can be drawn.
                        " Most often you will deal with Drawable as the type of resource
                        retrieved for drawing things to the screen; the Drawable class provides
                        a generic API for dealing with an underlying visual resource that may
                        take a variety of forms. Unlike a View, a Drawable does not have any
                        facility to receive events or otherwise interact with the user.
                */

                // Get the image from drawable resource as drawable object
                Drawable drawable = getDrawable(R.drawable.panda);

                /*
                    BitmapDrawable
                        A Drawable that wraps a bitmap and can be tiled, stretched, or aligned.
                        You can create a BitmapDrawable from a file path, an input stream,
                        through XML inflation, or from a Bitmap object.
                */

                /*
                    public final Bitmap getBitmap ()
                        Returns the bitmap used by this drawable to render. May be null.
                */
                // Get the bitmap from drawable object
                Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();

                // Display the original image on ImageView
                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.
                */
                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 with WEBP format and quality 25%
                bitmap.compress(Bitmap.CompressFormat.WEBP,25,stream);

                /*
                    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.
                */
                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.
                */
                Bitmap compressedBitmap = BitmapFactory.decodeByteArray(byteArray,0,byteArray.length);

                // Display the compressed bitmap in ImageView
                iv_compressed.setImageBitmap(compressedBitmap);
            }
        });
    }
}

More android examples