Need help?

Image Compression in Android

In this Image Compression in Android tutorial, I will explain how to pick an image from Gallery or Camera and compress it before uploading it.

I am sharing this code because the maximum android app has a user account. If a user creates his account, the profile picture needs to be added compulsory. We need to pick a picture from Gallery or Camera. Some applications depend on media like Facebook or Instagram to source the image. My article will increase your understanding on how to compress images in Android.

So let’s start with the following design and requirement

  1. The screen shows the two Image view on the top of the screen one for showing selected image and second for showing compressed image.
  2. Below this Image view, we have used three buttons. First to pick image from the gallery, second to pick image from the camera and the third button to compress the selected image.
  3. After clicking on the button “Load From Gallery”, user gets redirected to the gallery where he can select an image. He can also use “Load From Camera” option to use inbuilt device camera and take a new photo which will be set to top Image view.
  4. After clicking on ‘Compress’ button, the selected image from the gallery or camera will get compressed and set to top Image view.

Here's How We Did Image Compression in Android Application

Request Case Study

Let’s start with code

1. Create a basic android project
Go to Android Studio | File | New | New Project

2. Our app needs two permissions in our AndroidManifest.xml file

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

3. Now we need a simple layout file with above mention design i.e. 2 Image view and 3 Buttons. Create new layout file i.e.layout/activity_main

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

 <LinearLayout
 android:id="@+id/activity_main_ll_lable"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_alignParentTop="true"
 android:layout_marginTop="10dp"
 android:orientation="horizontal">

 <TextView
 android:layout_width="0dp"
 android:layout_height="match_parent"
 android:layout_weight="1"
 android:gravity="center"
 android:text="@string/normal_image" />

 <TextView
 android:layout_width="0dp"
 android:layout_height="match_parent"
 android:layout_weight="1"
 android:gravity="center"
 android:text="@string/compress_image" />
 </LinearLayout>

 <LinearLayout
 android:id="@+id/activity_main_ll_image"
 android:layout_width="match_parent"
 android:layout_height="300dp"
 android:layout_below="@+id/activity_main_ll_lable"
 android:layout_marginTop="10dp"
 android:orientation="horizontal">

 <ImageView
 android:id="@+id/activity_main_img"
 android:layout_width="0dp"
 android:layout_height="match_parent"
 android:layout_weight="1"
 app:srcCompat="@mipmap/ic_launcher" />

 <ImageView
 android:id="@+id/activity_main_img_compress"
 android:layout_width="0dp"
 android:layout_height="match_parent"
 android:layout_weight="1"

 app:srcCompat="@mipmap/ic_launcher" />
 </LinearLayout>

 <Button
 android:id="@+id/activity_main_btn_load_from_gallery"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_below="@+id/activity_main_ll_image"
 android:layout_centerHorizontal="true"
 android:layout_marginTop="20dp"
 android:text="@string/load_from_gallery" />

 <Button
 android:id="@+id/activity_main_btn_load_from_camera"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_below="@+id/activity_main_btn_load_from_gallery"
 android:layout_centerHorizontal="true"
 android:layout_marginTop="10dp"
 android:text="@string/load_from_camera" />

 <Button
 android:id="@+id/activity_main_btn_compress"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_alignEnd="@+id/activity_main_btn_load_from_camera"
 android:layout_alignLeft="@+id/activity_main_btn_load_from_gallery"
 android:layout_alignRight="@+id/activity_main_btn_load_from_camera"
 android:layout_alignStart="@+id/activity_main_btn_load_from_gallery"
 android:layout_below="@+id/activity_main_btn_load_from_camera"
 android:layout_marginTop="10dp"
 android:text="@string/compress" />
</RelativeLayout>

We also need some labels for Button and Imageview in values/strings.xml

<string name="load_from_gallery">Load From Gallery</string>
<string name="load_from_camera">Load From Camera</string>
<string name="compress">Compress</string>
<string name="normal_image">Normal Image</string>
<string name="compress_image">Compress Image</string>

4. Android code for picking the image from Gallery or Camera. “Load From Gallery”

Intent intentGalley = new Intent(Intent.ACTION_PICK);
intentGalley.setType("image/*");
startActivityForResult(intentGalley, PICK_GALLERY_IMAGE);

“Load From Camera”

destFile = new File(file, "img_"+ dateFormatter.format(new Date()).toString() + ".png");
imageCaptureUri = Uri.fromFile(destFile);
Intent intentCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, imageCaptureUri);
startActivityForResult(intentCamera, PICK_CAMERA_IMAGE);

When user selects image from Gallery or Camera, method onActivityResult() will be called in your main activity. Once you get the data in onActivityResult() , we need to handle it.

We are doing two operations on selected image.

i.Set to image view

ii.Copy selected image to another folder (Application folder) by using copyFile() method.

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
 super.onActivityResult(requestCode, resultCode, data);

 if (resultCode == Activity.RESULT_OK) {
 switch (requestCode) {
 case PICK_GALLERY_IMAGE:
 Uri uriPhoto = data.getData();
 Log.d(TAG + ".PICK_GALLERY_IMAGE", "Selected image uri path :" + uriPhoto.toString());

 img.setImageURI(uriPhoto);

 sourceFile = new File(getPathFromGooglePhotosUri(uriPhoto));

 destFile = new File(file, "img_"+ dateFormatter.format(new Date()).toString() + ".png");

 Log.d(TAG, "Source File Path :" + sourceFile);

 try {
 copyFile(sourceFile, destFile);
 } catch (IOException e) {
 e.printStackTrace();
 }
 break;
 case PICK_CAMERA_IMAGE:
 Log.d(TAG + ".PICK_CAMERA_IMAGE", "Selected image uri path :" + imageCaptureUri);
 img.setImageURI(imageCaptureUri);
 break;
 }
 }
}

5. Copy image from selected folder to application folder. If we want to copy an image from one folder to another folder, we need file path i.e. Source file and Destination file.

private void copyFile(File sourceFile, File destFile) throws IOException {
 if (!sourceFile.exists()) {
 return;
 }

 FileChannel source = null;
 FileChannel destination = null;
 source = new FileInputStream(sourceFile).getChannel();
 destination = new FileOutputStream(destFile).getChannel();
 if (destination != null && source != null) {
 destination.transferFrom(source, 0, source.size());
 }
 if (source != null) {
 source.close();
 }
 if (destination != null) {
 destination.close();
 }
}

 }
}

When we pick an image from gallery we got the image data from Uri format but we need a file to copy one folder to another. So now we are using one method getPathFromGooglePhotosUri() for getting string path from Uri.

public String getPathFromGooglePhotosUri(Uri uriPhoto) {
 if (uriPhoto == null)
 return null;

 FileInputStream input = null;
 FileOutputStream output = null;
 try {
 ParcelFileDescriptor pfd = getContentResolver().openFileDescriptor(uriPhoto, "r");
 FileDescriptor fd = pfd.getFileDescriptor();
 input = new FileInputStream(fd);

 String tempFilename = getTempFilename(this);
 output = new FileOutputStream(tempFilename);

 int read;
 byte[] bytes = new byte[4096];
 while ((read = input.read(bytes)) != -1) {
 output.write(bytes, 0, read);
 }
 return tempFilename;
 } catch (IOException ignored) {
 // Nothing we can do
 } finally {
 closeSilently(input);
 closeSilently(output);
 }
 return null;
}

public static void closeSilently(Closeable c) {
 if (c == null)
 return;
 try {
 c.close();
 } catch (Throwable t) {
 // Do nothing
 }
}

private static String getTempFilename(Context context) throws IOException {
 File outputDir = context.getCacheDir();
 File outputFile = File.createTempFile("image", "tmp", outputDir);
 return outputFile.getAbsolutePath();
}

6. Once you get the selected image in onActivityResult(), we will compress it and set it to another Imageview.

private Bitmap decodeFile(File f) {
 Bitmap b = null;

 //Decode image size
 BitmapFactory.Options o = new BitmapFactory.Options();
 o.inJustDecodeBounds = true;

 FileInputStream fis = null;
 try {
 fis = new FileInputStream(f);
 BitmapFactory.decodeStream(fis, null, o);
 fis.close();
 } catch (FileNotFoundException e) {
 e.printStackTrace();
 } catch (IOException e) {
 e.printStackTrace();
 }

 int IMAGE_MAX_SIZE = 1024;
 int scale = 1;
 if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
 scale = (int) Math.pow(2, (int) Math.ceil(Math.log(IMAGE_MAX_SIZE /
 (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
 }

 //Decode with inSampleSize
 BitmapFactory.Options o2 = new BitmapFactory.Options();
 o2.inSampleSize = scale;
 try {
 fis = new FileInputStream(f);
 b = BitmapFactory.decodeStream(fis, null, o2);
 fis.close();
 } catch (FileNotFoundException e) {
 e.printStackTrace();
 } catch (IOException e) {
 e.printStackTrace();
 }

 Log.d(TAG, "Width :" + b.getWidth() + " Height :" + b.getHeight());

 destFile = new File(file, "img_"
 + dateFormatter.format(new Date()).toString() + ".png");
 try {
 FileOutputStream out = new FileOutputStream(destFile);
 b.compress(Bitmap.CompressFormat.PNG, 100, out);
 out.flush();
 out.close();

 } catch (Exception e) {
 e.printStackTrace();
 }
 return b;
}

Get the compressed image in bitmap format and set to image view after clicking on compress button.

Bitmap bmp = decodeFile(destFile);
imgCompress.setImageBitmap(bmp);

 

Also Read: Branch.Io Deeplink In Android 

Final Code for activity

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

 private final String TAG = getClass().getSimpleName();

 private static final int PICK_CAMERA_IMAGE = 2;
 private static final int PICK_GALLERY_IMAGE = 1;

 public static final String DATE_FORMAT = "yyyyMMdd_HHmmss";
 public static final String IMAGE_DIRECTORY = "ImageScalling";

 private static final String SCHEME_FILE = "file";
 private static final String SCHEME_CONTENT = "content";

 private Button btnGallery;
 private Button btnCamera;
 private Button btnCompress;

 private ImageView img;
 private ImageView imgCompress;

 private Uri imageCaptureUri;

 private File file;
 private File sourceFile;
 private File destFile;

 private SimpleDateFormat dateFormatter;

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

 file = new File(Environment.getExternalStorageDirectory()
 + "/" + IMAGE_DIRECTORY);
 if (!file.exists()) {
 file.mkdirs();
 }

 dateFormatter = new SimpleDateFormat(
 DATE_FORMAT, Locale.US);

 initView();
 }

 public void initView() {
 btnGallery = (Button) findViewById(R.id.activity_main_btn_load_from_gallery);
 btnCamera = (Button) findViewById(R.id.activity_main_btn_load_from_camera);
 btnCompress = (Button) findViewById(R.id.activity_main_btn_compress);
 img = (ImageView) findViewById(R.id.activity_main_img);
 imgCompress = (ImageView) findViewById(R.id.activity_main_img_compress);

 btnGallery.setOnClickListener(this);
 btnCamera.setOnClickListener(this);
 btnCompress.setOnClickListener(this);
 }

 @Override
 public void onClick(View v) {
 switch (v.getId()) {
 case R.id.activity_main_btn_load_from_gallery:
 Intent intentGalley = new Intent(Intent.ACTION_PICK);
 intentGalley.setType("image/*");
 startActivityForResult(intentGalley, PICK_GALLERY_IMAGE);
 break;
 case R.id.activity_main_btn_load_from_camera:

 destFile = new File(file, "img_"
 + dateFormatter.format(new Date()).toString() + ".png");
 imageCaptureUri = Uri.fromFile(destFile);

 Intent intentCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
 intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, imageCaptureUri);
 startActivityForResult(intentCamera, PICK_CAMERA_IMAGE);
 break;
 case R.id.activity_main_btn_compress:
 Bitmap bmp = decodeFile(destFile);
 imgCompress.setImageBitmap(bmp);
 break;
 }

 }

 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
 super.onActivityResult(requestCode, resultCode, data);

 if (resultCode == Activity.RESULT_OK) {
 switch (requestCode) {
 case PICK_GALLERY_IMAGE:
 Uri uriPhoto = data.getData();
 Log.d(TAG + ".PICK_GALLERY_IMAGE", "Selected image uri path :" + uriPhoto.toString());

 img.setImageURI(uriPhoto);

 sourceFile = new File(getPathFromGooglePhotosUri(uriPhoto));

 destFile = new File(file, "img_"
 + dateFormatter.format(new Date()).toString() + ".png");

 Log.d(TAG, "Source File Path :" + sourceFile);

 try {
 copyFile(sourceFile, destFile);
 } catch (IOException e) {
 e.printStackTrace();
 }
 break;
 case PICK_CAMERA_IMAGE:
 Log.d(TAG + ".PICK_CAMERA_IMAGE", "Selected image uri path :" + imageCaptureUri);
 img.setImageURI(imageCaptureUri);
 break;
 }
 }
 }

 private Bitmap decodeFile(File f) {
 Bitmap b = null;

 //Decode image size
 BitmapFactory.Options o = new BitmapFactory.Options();
 o.inJustDecodeBounds = true;

 FileInputStream fis = null;
 try {
 fis = new FileInputStream(f);
 BitmapFactory.decodeStream(fis, null, o);
 fis.close();
 } catch (FileNotFoundException e) {
 e.printStackTrace();
 } catch (IOException e) {
 e.printStackTrace();
 }

 int IMAGE_MAX_SIZE = 1024;
 int scale = 1;
 if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
 scale = (int) Math.pow(2, (int) Math.ceil(Math.log(IMAGE_MAX_SIZE /
 (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
 }

 //Decode with inSampleSize
 BitmapFactory.Options o2 = new BitmapFactory.Options();
 o2.inSampleSize = scale;
 try {
 fis = new FileInputStream(f);
 b = BitmapFactory.decodeStream(fis, null, o2);
 fis.close();
 } catch (FileNotFoundException e) {
 e.printStackTrace();
 } catch (IOException e) {
 e.printStackTrace();
 }

 Log.d(TAG, "Width :" + b.getWidth() + " Height :" + b.getHeight());

 destFile = new File(file, "img_"
 + dateFormatter.format(new Date()).toString() + ".png");
 try {
 FileOutputStream out = new FileOutputStream(destFile);
 b.compress(Bitmap.CompressFormat.PNG, 100, out);
 out.flush();
 out.close();

 } catch (Exception e) {
 e.printStackTrace();
 }
 return b;
 }

 /**
 * This is useful when an image is available in sdcard physically.
 *
 * @param uriPhoto
 * @return
 */
 public String getPathFromUri(Uri uriPhoto) {
 if (uriPhoto == null)
 return null;

 if (SCHEME_FILE.equals(uriPhoto.getScheme())) {
 return uriPhoto.getPath();
 } else if (SCHEME_CONTENT.equals(uriPhoto.getScheme())) {
 final String[] filePathColumn = {MediaStore.MediaColumns.DATA,
 MediaStore.MediaColumns.DISPLAY_NAME};
 Cursor cursor = null;
 try {
 cursor = getContentResolver().query(uriPhoto, filePathColumn, null, null, null);
 if (cursor != null && cursor.moveToFirst()) {
 final int columnIndex = (uriPhoto.toString()
 .startsWith("content://com.google.android.gallery3d")) ? cursor
 .getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)
 : cursor.getColumnIndex(MediaStore.MediaColumns.DATA);

 // Picasa images on API 13+
 if (columnIndex != -1) {
 String filePath = cursor.getString(columnIndex);
 if (!TextUtils.isEmpty(filePath)) {
 return filePath;
 }
 }
 }
 } catch (IllegalArgumentException e) {
 // Nothing we can do
 Log.d(TAG, "IllegalArgumentException");
 e.printStackTrace();
 } catch (SecurityException ignored) {
 Log.d(TAG, "SecurityException");
 // Nothing we can do
 ignored.printStackTrace();
 } finally {
 if (cursor != null)
 cursor.close();
 }
 }
 return null;
 }

 /**
 * This is useful when an image is not available in sdcard physically but it displays into photos application via google drive(Google Photos) and also for if image is available in sdcard physically.
 *
 * @param uriPhoto
 * @return
 */
public String getPathFromGooglePhotosUri(Uri uriPhoto) {
 if (uriPhoto == null)
 return null;

 FileInputStream input = null;
 FileOutputStream output = null;
 try {
 ParcelFileDescriptor pfd = getContentResolver().openFileDescriptor(uriPhoto, "r");
 FileDescriptor fd = pfd.getFileDescriptor();
 input = new FileInputStream(fd);

 String tempFilename = getTempFilename(this);
 output = new FileOutputStream(tempFilename);

 int read;
 byte[] bytes = new byte[4096];
 while ((read = input.read(bytes)) != -1) {
 output.write(bytes, 0, read);
 }
 return tempFilename;
 } catch (IOException ignored) {
 // Nothing we can do
 } finally {
 closeSilently(input);
 closeSilently(output);
 }
 return null;
 }

 public static void closeSilently(Closeable c) {
 if (c == null)
 return;
 try {
 c.close();
 } catch (Throwable t) {
 // Do nothing
 }
 }

 private static String getTempFilename(Context context) throws IOException {
 File outputDir = context.getCacheDir();
 File outputFile = File.createTempFile("image", "tmp", outputDir);
 return outputFile.getAbsolutePath();
 }

 private void copyFile(File sourceFile, File destFile) throws IOException {
 if (!sourceFile.exists()) {
 return;
 }

 FileChannel source = null;
 FileChannel destination = null;
 source = new FileInputStream(sourceFile).getChannel();
 destination = new FileOutputStream(destFile).getChannel();
 if (destination != null && source != null) {
 destination.transferFrom(source, 0, source.size());
 }
 if (source != null) {
 source.close();
 }
 if (destination != null) {
 destination.close();
 }
 }
}

Conclusion

Most of the time, we face the issue when user pick a picture from Gallery or Camera(Mostly App Crash or taking to much time). Hope this Image Compression in Android tutorial will help you to eliminate the crashing and also avoid huge load time. Now you can easily compress image size in android programmatically. Get in touch with us If you want to hire dedicated android developer .

Subscribe To Our Newsletter

Content Team

This blog is from Mindbowser‘s content team – a group of individuals coming together to create pieces that you may like. If you have feedback, please drop us a message on contact@mindbowser.com
We do publish often and our blogs are often accompanied by research and surveys. If you would like to be the first to receive an update on whenever we publish, subscribe to our newsletter.

Leave a Reply

Your email address will not be published. Required fields are marked *