Monday, September 28, 2015

android - How to compress a bitmap

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="Compress Bitmap"
        />
    <ImageView
        android:id="@+id/iv_source"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/btn"
        android:padding="5dp"
        android:src="@drawable/bird"
        />
    <TextView
        android:id="@+id/tv_source"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/iv_source"
        android:text="Original Image"
        />
    <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="5dp"
        />
    <TextView
        android:id="@+id/tv_compressed"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/iv_source"
        android:layout_alignLeft="@id/iv_compressed"
        />
</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;
import android.widget.TextView;


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 TextView tv_compressed = (TextView) findViewById(R.id.tv_compressed);

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

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Get the image from drawable resource as drawable object
                Drawable drawable = getDrawable(R.drawable.bird);
                // Get the bitmap from drawable object
                Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();

                // Display the original image on ImageView
                iv_source.setImageBitmap(bitmap);

                // Initialize a new ByteArrayStream
                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.
                */

                /*
                    Bitmap.CompressFormat
                        Specifies the known formats a bitmap can be compressed into.

                            Bitmap.CompressFormat  JPEG
                            Bitmap.CompressFormat  PNG
                            Bitmap.CompressFormat  WEBP
                */
                // Compress the bitmap with JPEG format and quality 50%
                bitmap.compress(Bitmap.CompressFormat.JPEG,50,stream);

                byte[] byteArray = stream.toByteArray();
                Bitmap compressedBitmap = BitmapFactory.decodeByteArray(byteArray,0,byteArray.length);

                // Display the compressed bitmap in ImageView
                iv_compressed.setImageBitmap(compressedBitmap);
                tv_compressed.setText("Compressed Image / JPEG 50% Quality.");
            }
        });
    }
}

More android examples