Monday 5 December 2016

Image Compression in Android



Image Compression Library for Android

Handy Library to compress and upload images when the files are too large.
https://github.com/zetbaitsu/Compressor


Step 1:

Add below line to buid.gradle file

compile 'id.zelory:compressor:1.0.4'


Step 2:

MainActivity.java

1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package com.pratap.imagecompression;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;

import id.zelory.compressor.Compressor;
import id.zelory.compressor.FileUtil;


public class MainActivity extends AppCompatActivity {


    ImageView img_original, img_compressed;
    TextView txt_filePath;
    Button btnSelectImage;
    private File actualImage;
    private File compressedImage;


    private static final int PICK_IMAGE_REQUEST = 1;

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


        img_original = (ImageView) findViewById(R.id.img_original);
        img_compressed = (ImageView) findViewById(R.id.img_compressed);
        txt_filePath = (TextView) findViewById(R.id.txt_filePath);
        btnSelectImage = (Button) findViewById(R.id.btnSelectImage);


        btnSelectImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                chooseImage(view);


            }
        });
    }


    public void chooseImage(View view) {
        /*Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image*//*");
        startActivityForResult(intent, PICK_IMAGE_REQUEST);*/

        Intent i = new Intent(
                Intent.ACTION_PICK,
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

        startActivityForResult(i, PICK_IMAGE_REQUEST);

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK) {
            if (data == null) {
                showError("Failed to open picture!");
                return;
            }
            try {
                actualImage = FileUtil.from(this, data.getData());
// code to compress image and stores it Pictures folder 
                compressedImage = new Compressor.Builder(this)
                        .setMaxWidth(640)
                        .setMaxHeight(480)
                        .setQuality(90)
                        .setCompressFormat(Bitmap.CompressFormat.PNG)
                        .setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(
                                Environment.DIRECTORY_PICTURES).getAbsolutePath())
                        .build()
                        .compressToFile(actualImage);


                txt_filePath.setText(
                        String.format("Actual Size : %s", getReadableFileSize(actualImage.length()) + "" +
                                "\nActual FilePath : "+ actualImage.getAbsolutePath() +
                                String.format("\nCompressed Size : %s", getReadableFileSize(compressedImage.length()))+
                        "\nCompressed FilePath : "+ compressedImage.getAbsolutePath()
                ));

                img_original.setImageBitmap(BitmapFactory.decodeFile(actualImage.getAbsolutePath()));
                img_compressed.setImageBitmap(BitmapFactory.decodeFile(compressedImage.getAbsolutePath()));

            } catch (IOException e) {
                showError("Failed to read picture data!");
                e.printStackTrace();
            }
        }
    }


    public String getReadableFileSize(long size) {
        if (size <= 0) {
            return "0";
        }
        final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
        return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
    }


    public void showError(String errorMessage) {
        Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show();
    }
}



activity_main.xml
==============

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/img_original"
            android:layout_width="match_parent"
            android:layout_height="250dp"
            android:layout_weight="1"
            android:padding="1dp"
            android:scaleType="centerCrop" />

        <ImageView
            android:id="@+id/img_compressed"
            android:layout_width="match_parent"
            android:layout_height="250dp"
            android:layout_weight="1"
            android:padding="1dp"
            android:scaleType="centerCrop" />


    </LinearLayout>

    <TextView
        android:id="@+id/txt_filePath"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/linearLayout"
        android:layout_centerHorizontal="true"
        android:layout_margin="10dp"
        android:text="" />

    <Button
        android:id="@+id/btnSelectImage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:text="Select Image" />


</RelativeLayout>


Code Snippet that do compress the image
==============================
 compressedImage = new Compressor.Builder(this)
                        .setMaxWidth(640)
                        .setMaxHeight(480)
                        .setQuality(90)
                        .setCompressFormat(Bitmap.CompressFormat.PNG)
                        .setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(
                                Environment.DIRECTORY_PICTURES).getAbsolutePath())
                        .build()
                        .compressToFile(actualImage);


References:
https://github.com/zetbaitsu/Compressor

1 comment: